How do you do something like check all elements in a vector for some condition, and erase those that meet the condition?
I have always been doing something like this -
Code:
for (std::vector<T>::iterator it = v.begin(); it != v.end();)
{
std::vector<T>::iterator next = it + 1;
if (should_remove(*it))
{
v.erase(it);
}
it = next;
}
The problem is, I just realized, if the element removed is the last element, "it" will end up pointing to end()+1, and bad things will happen.
I can do a special case for last element, but is there a cleaner way?