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

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

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

would be enough. But for 2D, which does:

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

What is the right way to do this?
And how can I iterate over it using?

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

this is just for show: 10.1!

And by the way, what does that mean?

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

I saw it here and can't understand! Link

+4
source share
1 answer

What is the right way to do this?

The way you showed is a possible way. You can 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 builds a std::initializer_list<std::vector<int>> where the elements are directly initialized from internal lists with initializer binders. The second explicitly creates temporary vectors, which then move to std::initializer_list<std::vector<int>> . This probably will not make any difference, since this step can be eliminated.

In any case, the std::initializer_list<std::vector<int>> elements are copied back to myvect (you cannot exit std::initializer_list ).


And how can I iterate over it using for?

You have a vector of vectors, so 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 that mean?

This is probably a typo. In its current form, it is illegal. Declaration vector<int> myvect[5]; declares an array of 5 vector<int> . Therefore, the next time you initialize the list, you must initialize the array, but the elements of this list are implicitly converted to vector<int> (there is a ctor that accepts size_t , but it is explicit).

The comments on this side have already indicated .

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

+8
source

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


All Articles