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
?
To insert/append a vector's elements to another vector, we use vector::insert() function.
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().
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With