问题描述
如果我有两个向量,并希望将它们合并到一个向量,我可以这样做:
If I have two vectors and want to combine them to one, I can do it the following way:
std::vector<T> a(100); // just some random size here
std::vector<T> b(100);
a.insert(std::end(a), std::begin(b), std::end(b));
这涉及到复制,我想避免。有什么办法使用移动语义来获得它们吗?
我非常怀疑它,因为向量
应该是连续的。但是有任何方法可以用 deque
That involves copying though, which I want to avoid. Is there any way to use move-semantics to get them together?
I highly doubt it, as a vector
is supposed to be contiguous. However is there any way to do it with a deque
?
推荐答案
是,使用 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);
这篇关于“移动”两个向量在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!