aminfar - 7 months ago 38

C++ Question

I have two STL vectors

`A`

`B`

`A`

`B`

`A`

`B`

`std::vector<MyClass> A;`

std::vector<MyClass> B;

....

A = B;

B.clear();

Since

`B`

`k*O(N)`

`k`

`N`

`max(size_of(A), size_of(B))`

`A`

`B`

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