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.
Using C++11, it’s as simple as:
Now
Acontains the elements that were previously held byB, andBis now empty. This avoids copying: the internal representation is simply moved fromBtoA, so this is anO(1)solution.As for C++03, as Prætorian states, you could swap the vectors. There is a specialization of the
std::swapfunction, which takesstd::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 inO(1)complexity as well.