Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I move-append one std::vector to another?

Suppose I have an std::vector<T> from and std::vector<T> to where T is a non-copyable but moveable type and to may or may not be empty. I want all elements in from to be appended after to.

If I use the std::vector<T>::insert(const_iterator pos, InputIt first, InputIt last) overload (4) with pos = to.end(), it will attempt to copy all objects.

Now, if to.empty() I could just std::move(from) and otherwise I could first from.reserve(from.size()+to.size()) and then manually to.emplace_back(std::move(from[i])) every element of from and finally from.clear().

Is there a direct way of doing this with an std convenience function or wrapper?

like image 913
bitmask Avatar asked Sep 03 '26 23:09

bitmask


1 Answers

insert will work fine with std::move_iterator and std::make_move_iterator helper fucntion:

to.insert(to.end(),std::make_move_iterator(from.begin()),
    std::make_move_iterator(from.end()));
like image 61
rafix07 Avatar answered Sep 06 '26 13:09

rafix07