STL向量:移动向量的所有元素 [英] STL vector: Moving all elements of a vector
问题描述
我有两个STL向量 A
和 B
,我想清除<$ c的所有元素$ c> A 并将 B
的所有元素移动到 A
code> B 。简单地说,我想这样做:
I have two STL vectors A
and B
and I'd like to clear all elements of A
and move all elements of B
to A
and then clear out B
. Simply put, I want to do this:
std::vector<MyClass> A;
std::vector<MyClass> B;
....
A = B;
B.clear();
由于 B
可能很长, k * O(N)
执行此操作,其中 k
是常数, N
是 max(size_of(A),size_of(B))
。我想知道是否可以有一个更有效的方式这样做。我可以想到的一件事是定义 A
和 B
作为指针,然后复制指针在常量时间和清除out B
。
Since B
could be pretty long, it takes k*O(N)
to do this operation, where k
is a constant, and N
is max(size_of(A), size_of(B))
. I was wondering if there could be a more efficient way to do so. One thing that I could think of is to define A
and B
as pointers and then copy pointers in constant time and clear out B
.
推荐答案
使用C ++ 11 as:
Using C++11, it's as simple as:
A = std::move(B);
现在 A
由 B
持有, B
现在为空。这避免复制:内部表示简单地从 B
移动到 A
,所以这是一个 O(1)
解决方案。
Now A
contains the elements that were previously held by B
, and B
is now empty. This avoids copying: the internal representation is simply moved from B
to A
, so this is an O(1)
solution.
对于C ++ 03,如Prætorian所说,可以交换向量。有一个专门的 std :: swap
函数,它以 std :: vector
s为参数。这有效地交换内部表示,所以你最终避免创建他们持有的元素的副本。此函数在 O(1)
复杂性中也有效。
As for C++03, as Prætorian states, you could swap the vectors. There is a specialization of the std::swap
function, which takes std::vector
s as its arguments. This effectively swaps the internal representation, so you end up avoiding creating copies of the elements held by them. This function works in O(1)
complexity as well.
这篇关于STL向量:移动向量的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!