Home > Enterprise >  Initializing an array of vector
Initializing an array of vector

Time:12-31

I am trying to initialize an array of a vector of ints.

This is my code:

vector<int> *vec[] = new vector<int>[n 1];

I get the following compilation error:

initialization with '{...}' expected for aggregate object

What's wrong with this ?

CodePudding user response:

The problem is that you're trying to initialize an array of pointers to vector with a "pointer to a vector".

To solve this you can either remove the [] from the left hand side of the declaration or not mix std::vector and raw pointers.

//--------------v----------------------->removed [] from here
vector<int> *vec = new vector<int>[n 1];

CodePudding user response:

If you need an array (in the broad sense) of elements of type vector<int>, I advise you to use:

std::vector<std::vector<int>> vec(n 1);

vec will be a vector of vectors. The number of vectors will be n 1 like it seems you wanted. std::vector will manage the memory for you, so there's no need for new/delete.

In C we also have std::array, but it looks like the number of elements in vec is dynamically dependant on n, which makes a topmost std::vector the proper fit.

There are many advantages using C std::vector/std::array over c style arrays. See e.g. the answers here: std::vector versus std::array in C .

If you must use a C style topmost array, see the other answer.

  • Related