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
The way you showed is a possible way. You could also use:
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 astd::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 intomyvect
(you cannot move out of astd::initializer_list
).You essentially have a vector of vectors, therefore you need two loops:
I refrained from using
auto
to explicitly show the resulting types.This is probably a typo. As it stands, it's illegal. The declaration
vector<int> myvect[5];
declares an array of 5vector<int>
. The following list-initialization therefore needs to initialize the array, but the elements of this list are not implicitly convertible tovector<int>
(there's a ctor that takes asize_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};
.