aminfar aminfar - 2 months ago 9
C++ Question

STL vector: Moving all elements of a vector

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();


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
.

Answer

Using C++11, it's as simple as:

A = std::move(B);

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.

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::vectors 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.