简体   繁体   中英

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 thestd::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?

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()));
#include<iterator>

std::vector<T> source = {...};

std::vector<T> destination;

std::move(source.begin(), source.end(), std::back_inserter(destination));

You may want to consider the std::move() algorithm – ie, the moving counterpart of std::copy() – instead of the std::move() convenience template function:

#include <vector>
#include <algorithm>

struct OnlyMovable {
   OnlyMovable() = default;
   OnlyMovable(const OnlyMovable&) = delete;
   OnlyMovable(OnlyMovable&&) = default;
};

auto main() -> int {
   std::vector<OnlyMovable> from(5), to(3);
   std::move(from.begin(), from.end(), std::back_inserter(to)); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM