rhue
rhue

Reputation: 35

C++ Dynamic arrays of templated classes (i.e. vector)

I'm currently in the progress of teaching myself C++ and try to implement a simple hashmap (with two template classes ).

However, I can't figure out how to initialize a dynamic array of vectors correctly. My attempts which have failed:

std::vector<Key> *keys = new std::vector<Key>[size];
std::vector<Key> *keys = (std::vector<Key> *) malloc(sizeof(std::vector<Key>) * size);
std::vector<Key> **keys = reinterpret_cast<vector<Key> **>(malloc(sizeof(vector<Key>) * size));

Or was I doing somewhere else something wrong? :(

Upvotes: 0

Views: 849

Answers (2)

EdChum
EdChum

Reputation: 394159

What you are doing is unnecessary, vector supports dynamic sizing and you do not need to new it.

So:

std::vector<Key> keys = std::vector<Key>(size); // is fine to initialise the vector to a specific size.

if you want to have a pointer to a vector of then you could new like so

std::vector<Key>* keys = new std::vector<Key>(size);

Also you can always add and remove elements on demand and it will resize if necessary or you can force it:

keys.resize(newSize); // note that if the new size is larger than current size
// it will default fill the new elements so if your `vector` is of `ints` 
// then it will pad with zeros.

Upvotes: 1

KCH
KCH

Reputation: 2854

You should do it this way:

std::vector<Key> *keys = new std::vector<Key>(size);

Even if one of those attempts worked:

std::vector<Key> *keys = (std::vector<Key> *) malloc(sizeof(std::vector<Key>) * size);
std::vector<Key> **keys = reinterpret_cast<vector<Key> **>(malloc(sizeof(vector<Key>) * size));

it would allocate memory, but not create object as it won't call its constructor.

Upvotes: 0

Related Questions