Home > Blockchain >  Move one more vector to the vector of vectors?
Move one more vector to the vector of vectors?

Time:11-02

I have the structure vector<vector<x>> a and one more vector<x> v. I need to append this new vector to the existing vector of vectors (as new a item, not to concatenate), but it is long and I do not need it afterwards, so I would like to move the contents instead:

As of the time of writing, the code is trivial:

 a.push_back(v);

that obviously works. Can this be optimized like

 a.push_back(std::move(v));

or somehow else?

CodePudding user response:

Yes, this will definitely work. As you can read in the definition of std::move here,

std::move is used to indicate that an object t may be "moved from", i.e. allowing the efficient transfer of resources from t to another object. In particular, std::move produces an xvalue expression that identifies its argument t. It is exactly equivalent to a static_cast to an rvalue reference type.

So the result can be interpreted as rvalue reference.

And if we then look at the description of the std::vectors push_back function here, then we will find

void push_back( T&& value )

which will "move the value into the new element"

So, your approach will work.

  • Related