suppose we have an array of int
, and now we want to convert to vector
of vector
, in condition that all number less than or equal 5 must be the first element of the sub-vector of the new vector vv
, and also the length of each sub-vector should no bigger than 3. //
int array[] = {9, 8, 6, 5, 4, 8, 9, 7, 6, 5};
and it should be converted to
vv = { { 9, 8, 6 }, { 5 }, { 4, 8, 9 }, { 7, 6 }, { 5 } };
In order to do that, I can loop through the array and found the elements of the next sub-vector to emplace_back. So that I am considering that after finding the numbers to to pushed back, create temporary vector in-place.
Say, I found 9, 8, 6 goes to the next sub-vector, and 5 goes to next after, we do:
vector< vector < int > > vv;
vector < int > v
v.push_back(9);
v.push_back(8);
v.push_back(6);
vv.push_back(v);
v.clear();
v.push_back(5);
vv.push_back(v)
v.clear();
Now vv is { { 9, 8, 6 }, { 5 } }. This is quite cumbersome. Can I have the temporary vector created in-place to emplace_back directly to achieve the same result.
vv.emplace_back( vector <int > ( 3, 9, 8, 6 ) ); // this is wrong
vv.emplace_back( vector< int > ( 1, 5 ) ); // this is good.
or equivalently,
vv.emplace_back( vector <int > { 9, 8, 6 } ); // this is good.
vv.emplace_back( vector< int > ( 1, 5 ) ); // this is good too.
Thanks!
If you know the values in advance you can just do list initialization:
std::vector<std::vector<int>> vv{
{ 9, 8, 6 }, { 5 }
};
You can do:
vector< vector < int > > vv;
...
vv = { { 9, 8, 6 }, { 5 } };
or:
vector< vector < int > > vv;
...
vv.emplace_back( { 9, 8, 6 } );
vv.emplace_back( { 5 } );
you should not create temporary explicitly when calling emplace_back
method you basically make it equivalent to push_back
, whole point of emplace
is to forward parameters to element ctor directly (same for emplace
methods in other containers).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.