Omegon
Omegon

Reputation: 461

what is the best way to move the elements: the whole vector or move + erase for the elements?

I'm wondering how best to move elements from one vector to another .Let's say you can do this :

std::vector<int> v(10);
std::fill(std::begin(v), std::end(v), 5);
std::vector<int> move_v = std::move(v);

And then everything works as I thought: std::size(v) prints 0, and in another vector the elements appeared. On the other hand.

I have seen that it is often suggested to do something like this:

std::vector<int> v(10);
std::vector<int> move_v(10);
std::fill(std::begin(v), std::end(v), 5);

std::move(std::begin(v), std::end(v), std::begin(move_V));
v.erase(std::begin(v), std::end(v));

But it doesn't work quite as well as I expect.Why are the elements after std::move not moved here,that is, here the elements in the vector v remain in place.And we need to call the erase function .Are they being moved or are they being copied?Actually, I wonder which approach is considered better ?

Upvotes: 0

Views: 92

Answers (1)

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29985

In the first example, you're moving the whole vector at once. This is presumably what you want. Just copy a couple of pointers, you're done. O(1) complexity and everything is good.

In the second example, you're moving every element individually. This means that you're trying to move integers, which is the same as copying. So, no moving takes place. This is probably not what you want.

Upvotes: 3

Related Questions