C++11 – Initializing a 2D Vector Using Initialization List

c++11stdvector

How can i initialize a 2D vector using an initialization list?
for a normal vector doing :

vector<int> myvect {1,2,3,4};

would suffice. But for a 2D one doing :

vector<vector<int>> myvect{ {10,20,30,40},
                            {50,60,70,80}
                          };

What is a correct way of doing it?
And how can i iterate through it using for?

for(auto x: myvect)
{
    cout<<x[j++]<<endl;
}

this for only shows:
10,1 !

And by the way what does this mean ?

   vector<int> myvect[5] {1,2,3,4};

i saw it here and cant understand it! Link

Best Answer

What is a correct way of doing it?

The way you showed is a possible way. You could also use:

vector<vector<int>> myvect = { {10,20,30,40},
                               {50,60,70,80} };

vector<vector<int>> myvect{ vector<int>{10,20,30,40},
                            vector<int>{50,60,70,80} };

The first one constructs a std::initializer_list<std::vector<int>> where the elements are directly initialized from the inner braced-initializer-lists. The second one explicitly constructs temporary vectors which then are moved into a std::initializer_list<std::vector<int>>. This will probably not make a difference, since that move can be elided.

In any way, the elements of the std::initializer_list<std::vector<int>> are copied back out into myvect (you cannot move out of a std::initializer_list).


And how can i iterate through it using for?

You essentially have a vector of vectors, therefore you need two loops:

for(vector<int> const& innerVec : myvect)
{
    for(int element : innerVec)
    {
        cout << element << ',';
    }
    cout << endl;
}

I refrained from using auto to explicitly show the resulting types.


And by the way what does this mean ?

This is probably a typo. As it stands, it's illegal. The declaration vector<int> myvect[5]; declares an array of 5 vector<int>. The following list-initialization therefore needs to initialize the array, but the elements of this list are not implicitly convertible to vector<int> (there's a ctor that takes a size_t, but it's explicit).

That has already been pointed out in the comments of that side.

I guess the author wanted to write std::vector<int> vArray = {3, 2, 7, 5, 8};.

Related Question