Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I move the contents of one vector to the end of another?

I want to do something like the following (a and b are both vector<my_moveable_type>):

a.insert(a.end(), b.begin(), b.end());

But I want the operation to move b's elements into a instead of copying them. I have found std::vector::emplace but that is just for a single element, not a range.

Can this be done?

like image 647
fbrereto Avatar asked Aug 10 '13 06:08

fbrereto


People also ask

How do you add a vector to the end of another vector C++?

Appending a vector elements to another vector 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 get to the end of a vector?

The immediate answer to your question as to fetching access to the last element in a vector can be accomplished using the back() member. Such as: int var = vec. back().

Can vector be moved?

Yes, you can move vectors.

Can you add a vector to another vector?

Two vectors can be added together to determine the result (or resultant).


1 Answers

You can use std::make_move_iterator, so that accesses to the iterator returns rvalue references instead of lvalue references:

a.insert(a.end(), std::make_move_iterator(b.begin()), std::make_move_iterator(b.end()));
like image 87
Nicol Bolas Avatar answered Sep 29 '22 06:09

Nicol Bolas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!