stdvector - Initializing a 2D vector using initialization list in C++11 -
how can initialize 2d vector using initialization list? normal vector doing :
vector<int> myvect {1,2,3,4};
would suffice. 2d 1 doing :
vector<vector<int>> myvect{ {10,20,30,40}, {50,60,70,80} };
what correct way of doing it?
, how can iterate through using for?
for(auto x: myvect) { cout<<x[j++]<<endl; }
this shows: 10,1 !
and way mean ?
vector<int> myvect[5] {1,2,3,4};
i saw here , cant understand it! link
what correct way of doing it?
the way showed possible way. 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 1 constructs std::initializer_list<std::vector<int>>
elements directly initialized inner braced-initializer-lists. second 1 explicitly constructs temporary vectors moved std::initializer_list<std::vector<int>>
. not make difference, since move can elided.
in way, elements of std::initializer_list<std::vector<int>>
copied out myvect
(you cannot move out of std::initializer_list
).
and how can iterate through using for?
you have vector of vectors, therefore need 2 loops:
for(vector<int> const& innervec : myvect) { for(int element : innervec) { cout << element << ','; } cout << endl; }
i refrained using auto
explicitly show resulting types.
and way mean ?
this typo. stands, it's illegal. declaration vector<int> myvect[5];
declares array of 5 vector<int>
. following list-initialization therefore needs initialize array, elements of list not implicitly convertible vector<int>
(there's ctor takes size_t
, it's explicit).
that has been pointed out in comments of side.
i guess author wanted write std::vector<int> varray = {3, 2, 7, 5, 8};
.
Comments
Post a Comment