user112513312
user112513312

Reputation: 509

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

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?

Upvotes: 12

Views: 15664

Answers (1)

NathanOliver
NathanOliver

Reputation: 180510

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.

Upvotes: 20

Related Questions