Initializing a 2D vector using initialization list in C++11

拥有回忆 提交于 2019-12-09 16:13:40

问题


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


回答1:


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};.



来源:https://stackoverflow.com/questions/17714552/initializing-a-2d-vector-using-initialization-list-in-c11

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!