Std :: vector :: erase vs "swap and pop"

The β€œnormal” way to remove an element from a vector is as follows:

vec.erase(vec.begin() + index); 

But theoretically this is faster, just for this:

 if (vec.size() >= 2) { std::swap(vec.begin() + index, vec.end() - 1); vec.pop_back(); } else { vec.clear(); } 

Is there a reason not to use the latter?

+5
source share
1 answer

The second case does not preserve the order of elements in the vector. If this is a sorted vector or order is important, then you just violated this in the second case, when the first case left the order intact.

+10
source

Source: https://habr.com/ru/post/1241419/


All Articles