Possible Duplicate:
Can you remove elements from a std::list while iterating through it?
I have a loop in a function, that iterates over an std::list from begin to end.
In each cycle, I perform some checks and maybe do a few manipulations on the current list entry, and in some cases I want to remove it from the list.
Now, as expected my iterator gets invalidated.
- Is there any way to work around this, to remove elements from a list while iterating over it?
Use postfix increment.
itis increased, so it no longer refers to the erased element, then the previous value ofitis given tolist.erase. Make sure that you either dolist.erase(it++)or++itin your loop – doing both will skip elements and potentially increment past end of the list.