Removing from a list
I'm iterating over a list and I want to remove certain elements from the list but because the list is resizable I'm not quite sure how to do it. In java I would think to use a list iterator. Here's my basic code:
But the list resizes so if I remove the last element then it will never equal to myQueue.end(). The thing I don't understand is, does myQueue.end point to the last element in the list? I've seen this type of loop used a lot to iterate over a loop but it looks like it will always miss the last element because of the != case, unless the for condition is evaluated at the end.
for(list<Obj*>::iterator it = myQueue.begin();it!=myQueue.end();it++)
Should I take out the it--?
Since erase() returns an iterator to the element after the one that was erased, I think you'll need it in there, otherwise you'll be skipping over some elements without checking if they match your condition.
Originally Posted by jcafaro10
The idomatic form of erasing certain elements whilst iterating through a container is:
Note the empty part of the for loop between the last semicolon and the close bracket. Use this loop form every time and you wont have any trouble.
for (ContainerType::iterator it = container.begin(); it!=container.end(); )
it = container.erase(it);
There are other options such as the erase/remove_if method that allow you to do the whole thing in one line too.