Creating and initializing an array of vectors at a time

To create an array of strings, this works:

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

If I try to do the same with vectors, this will not work:

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

I get that "non-aggregates cannot be initialized using a list of initializers."

What is the correct syntax for initializing an array of vectors?

Note that I need to do this at a time, and not use the vector member functions to populate the vectors intone at a time (because I'm trying to set up a file that will create an array at compile time based on the initialization numbers, so calling the member functions in this case does not help).

+3
source share
4 answers

( ?), , , :

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

, , , :

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

, std::vector . , , (.. , , const, , resize, reserve, push_back, insert, erase ), . .

, , . , , :

int fixed_size_array[100];

, . - - ++, , , .

+2

, . (, Boost:: assign), , - - , push_back.

+1

, - ?

const int arr[] = { 1, 2, 3, 4, 5 };

std::vector v( arr, arr + sizeof(arr) / sizeof(*arr) );
+1

std::vector< std::vector< int > > v;

no argument int

int arry[] = {1,2,3,4,5};
std::vector< int > list(arry, arry + sizeof(arry) / sizeof(int));

Thus, a vector is constructed from an Integer array. I would recommend that you use the push_back()Instead method in your script.

However, if you just want it dirty, you can follow the path described above and create an array std::vector< int >and pass it to the constructorstd::vector< std::vector< int > >

Check http://www.cplusplus.com/reference/stl/vector/vector/ for more information. You may be interested in this particular constructor overload.template <class InputIterator> vector ( InputIterator first, InputIterator last, const Allocator& = Allocator() );

Neel

0
source

Source: https://habr.com/ru/post/1750565/


All Articles