Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving elements from std::vector to another one

Tags:

c++

vector

How can I move some elements from first vector to second, and the elements will remove from the first?
if I am using std::move, the elements not removed from first vector.
this is the code I wrote:

   move(xSpaces1.begin() + 7, xSpaces1.end(), back_inserter(xSpaces2)); 
like image 297
user1544067 Avatar asked Feb 21 '13 14:02

user1544067


People also ask

How do you transfer elements from one vector to another?

To insert/append a vector's elements to another vector, we use vector::insert() function. Syntax: //inserting elements from other containers vector::insert(iterator position, iterator start_position, iterator end_position);

How do you add elements to a vector to another vector?

Use the insert Function to Append Vector to Vector in C++ The insert method is a built-in function of the std::vector container that can add multiple elements to the vector objects.

How do I copy a vector array to another?

Begin Initialize a vector v1 with its elements. Declare another vector v2 and copying elements of first vector to second vector using constructor method and they are deeply copied. Print the elements of v1. Print the elements of v2.

What happens when you std :: move a vector?

std::move. 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.


2 Answers

Resurrecting an old thread, but I am surprised that nobody mentioned std::make_move_iterator combined with insert. It has the important performance benefit of preallocating space in the target vector:

v2.insert(v2.end(), std::make_move_iterator(v1.begin() + 7),                      std::make_move_iterator(v1.end())); 

As others have pointed out, first vector v1 is now in indeterminate state, so use erase to clear the mess:

v1.erase(v1.begin() + 7, v1.end()); 
like image 149
Miljen Mikic Avatar answered Sep 21 '22 19:09

Miljen Mikic


std::move and std::copy operate on elements, not containers. You have to mutate the container separately. For example, to move the first 17 elements of v1 into a new vector v2:

std::vector<Foo> v1, v2;  // populate v1 with at least 17 elements...  auto it = std::next(v1.begin(), 17);  std::move(v1.begin(), it, std::back_inserter(v2));  // ##  v1.erase(v1.begin(), it); 

After line ##, the first 17 elements of v1 are still there, but they've been "moved-from", so they're in an indeterminate state.

like image 33
Kerrek SB Avatar answered Sep 20 '22 19:09

Kerrek SB