且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

“移动”两个向量在一起

更新时间:2023-11-18 09:32:22

是,使用 std :: move

#include <algorithm>
std::move(b.begin(), b.end(), std::back_inserter(a));

或者,您可以使用move iterators:

Alternatively, you can use move iterators:

a.insert(a.end(),
         std::make_move_iterator(b.begin()), std::make_move_iterator(b.end()));

请记住 #include< iterator> 在这两种情况下,在开始之前,请说:

Remember to #include <iterator> in both cases, and before you begin, say:

a.reserve(a.size() + b.size());

根据值初始化的成本,与检查和增加大小计数器相比,以下变体可能也很有趣:

Depending on the cost of value-initialization compared to checking and incrementing the size counter, the following variant may also be interesting:

std::size_t n = a.size();
a.resize(a.size() + b.size());
std::move(b.begin(), b.end(), a.begin() + n);