Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"move" two vectors together

If I have two vectors and want to combine them to one, I can do it the following way:

std::vector<T> a(100); // just some random size here std::vector<T> b(100);  a.insert(std::end(a), std::begin(b), std::end(b)); 

That involves copying though, which I want to avoid. Is there any way to use move-semantics to get them together?
I highly doubt it, as a vector is supposed to be contiguous. However is there any way to do it with a deque?

like image 468
Stephan Dollberg Avatar asked Mar 19 '12 21:03

Stephan Dollberg


People also ask

How do you combine two vectors?

The concatenation of vectors can be done by using combination function c. For example, if we have three vectors x, y, z then the concatenation of these vectors can be done as c(x,y,z). Also, we can concatenate different types of vectors at the same time using the same same function.

How do you append a vector to another 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(). The official function to be used to append is push_back().

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.


2 Answers

Yes, use std::move:

#include <algorithm> std::move(b.begin(), b.end(), std::back_inserter(a)); 

Alternatively, you can use move iterators:

a.insert(a.end(),          std::make_move_iterator(b.begin()), std::make_move_iterator(b.end())); 

Remember to #include <iterator> in both cases, and before you begin, say:

a.reserve(a.size() + b.size()); 

Depending on the cost of value-initialization compared to checking and incrementing the size counter, the following variant may also be interesting:

std::size_t n = a.size(); a.resize(a.size() + b.size()); std::move(b.begin(), b.end(), a.begin() + n); 
like image 189
Kerrek SB Avatar answered Sep 21 '22 19:09

Kerrek SB


Depends on exactly what you want to move. When you move a vector, it is done by effectively swapping the internal array pointer. So you can make one vector point to the array previously owned by another vector.

But that won't let you merge two vectors.

The best you can do then is to move every individual member element, as shown in Kerrek's answer:

std::move(b.begin(), b.end(), std::back_inserter(a)); 

Again, this will iterate through the vector and move every element to the target vector.

like image 26
jalf Avatar answered Sep 22 '22 19:09

jalf