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

user112513312 picture user112513312 · Jan 25, 2016 · Viewed 8.5k times · Source

The "normal" way of deleting an element from a vector goes like this:

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

But in theory it's faster just to do this:

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

Is there any reason to not use the latter?

Answer

NathanOliver picture NathanOliver · Jan 25, 2016

The second case does not preserve the order of the elements in the vector. If this is a sorted vector or the order is important then you have just broken that in the second case where the first case would leave the order intact.