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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With