Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use c++11 move semantics to append vector contents to another vector?

Consider this snippet:

class X;  void MoveAppend(vector<X>& src, vector<X>& dst) {    dst.reserve(dst.size() + src.size());    for (const X& x : src) dst.push_back(x);    src.clear(); } 

If we assume that class X implements move semantics, how can I efficiently implement MoveAppend?

like image 959
Łukasz Lew Avatar asked Jun 09 '13 13:06

Łukasz Lew


People also ask

How do you append one vector to another vector?

To insert/append a vector's elements to another vector, we use vector::insert() function.

Can I append vector to a vector C++?

How do you append to a Vector in C++? Appending to a vector means adding one or more elements at the back of the vector. The C++ vector has member functions. The member functions that can be used for appending are: push_back(), insert() and emplace().

How do you move an element in C++?

std::move in C++ Moves the elements in the range [first,last] into the range beginning at result. The value of the elements in the [first,last] is transferred to the elements pointed by result. After the call, the elements in the range [first,last] are left in an unspecified but valid state.

How do you add an element to an array in vector?

Insertion: Insertion in array of vectors is done using push_back() function. Above pseudo-code inserts element 35 at every index of vector <int> A[n]. Traversal: Traversal in an array of vectors is perform using iterators.


1 Answers

Just do:

#include <iterator> #include <algorithm>  // ...  void MoveAppend(std::vector<X>& src, std::vector<X>& dst)  {     if (dst.empty())     {         dst = std::move(src);     }     else     {         dst.reserve(dst.size() + src.size());         std::move(std::begin(src), std::end(src), std::back_inserter(dst));         src.clear();     } } 

If dst is empty, a move-assignment from src to dst will do the job - that will be as cheap as it can be, just "stealing" the array encapsulated by src so that dst will point to it afterwards.

If dst is not empty, elements appended to dst will be move-constructed from elements in src. After the call to std::move(), src will not be empty - it will contain "zombie" moved-from elements. That's why the call to clear() is still necessary.

like image 136
Andy Prowl Avatar answered Oct 01 '22 08:10

Andy Prowl