Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create and initialise an array of vectors in one go

Tags:

c++

vector

To create an array of strings this works:

std::string array[] = {
    "first",
    "second",
    :
    "last"
};

If I try to do the same with vectors it doesn't work:

std::vector<int> array[] = {
    {1, 2},
    {3, 4, 5}
    :
    {9}
};

I get "non-aggregates cannot be initialized with initializer list".

What is the correct syntax to initialise the array of vectors?

Note that I need to do it in one go like this and not using vector member functions to fill the vectors with ints one at a time (because I'm trying to set up a file that will create the array at compile time based upon the initialisation numbers, so calling member functions doesn't help in this case).

like image 666
Ian Avatar asked Oct 30 '25 22:10

Ian


1 Answers

Although the purpose of using an array of vectors is very much questionable (why not use vector of vectors or a two-dimentional array then?), to do what you want the correct syntax would look like:

std::vector<int> array[] = {
    vector<int>(2),
    vector<int>(3),
    //...
    vector<int>(1)
};

The reason it doesn't make any sense, is because in this case it's semantically the same as creating an array of pointers:

int* array[] = {
        new int[0],
        new int[0],
        //...
        new int[0],
    };

with the only difference is that internally std::vector is managing the lifetime of these pointers all by itself. That means that unless you're creating a constant-size vector (i.e. without a possibility for the vector to have its internal memory re-allocated, which is possible, if you're either declaring the vector to be const or simply make sure you don't ever call resize, reserve, push_back, insert, erase and other similar methods on it), you're going to get effectively an array of small objects with a pointer inside. This is how vector is usually implemented.

It's not clear, what you mean by creating an array on compile time. Arrays declared in the manner you try to do, as well as these:

int fixed_size_array[100];

are indeed created in such a way, than their size is determined on compile time. But vectors are a different beast -- these are complex C++ objects, which manage their memory dynamically in run-time, which means that they simply cannot have a compile-time fixed size by design.

like image 199
Andrei Sosnin Avatar answered Nov 02 '25 11:11

Andrei Sosnin