Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 827
user112513312 Avatar asked Jan 25 '16 13:01

user112513312


1 Answers

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.

like image 198
NathanOliver Avatar answered Oct 11 '22 10:10

NathanOliver