如何将一个 std::vector 移动附加到另一个?

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

假设我有一个 std::vector<T> fromstd::vector<T> to,其中 T 是不可复制但可移动的类型,而 to 可能为空也可能不为空。我希望 from 中的所有元素都附加在 to 之后。

如果我将 std::vector<T>::insert(const_iterator pos, InputIt first, InputIt last) 重载 (4) 与 pos = to.end() 一起使用,它将尝试 复制 所有对象。

现在,如果 to.empty() 我可以 std::move(from),否则我可以先 from.reserve(from.size()+to.size()) 然后手动 to.emplace_back(std::move(from[i])) from 的每个元素,最后 from.clear().

是否有使用 std 便捷函数或包装器的直接方法?

#include<iterator>

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

std::vector<T> destination;

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

您可能需要考虑 std::move() algorithm – i.e., the moving counterpart of std::copy() – instead of the std::move() 方便的模板函数:

#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)); 
}

insert 将与 std::move_iterator and std::make_move_iterator 辅助函数一起正常工作:

to.insert(to.end(),std::make_move_iterator(from.begin()),
    std::make_move_iterator(from.end()));