So, in short: generally speaking, you should not delete the items from
the list while iterating through it, because the deletion may invalidate
the iterator (and the program will possibly crash). If you are however
completely sure that the items which you delete are not the values
referenced by any of the iterators which you use at the moment of
deletion, you may delete.
Beware that for the other STL containers (e.g. vectors) the constraint
is even more strict: deleting from the container invalidates not only
iterators pointing to the deleted item, but possibly other iterators, too!
So deleting from that containers while iterating through them is even
more problematic.
Choose carefully among erasing options: To eliminate all objects in a
container that have a particular value.
For vector, string or deque, use erase-remove. Don’t use forloop, it will invalid the iterator.
For a list, use it’s own remove or remove_if.
For associative container, use its erase member function.
To eliminate all objects in a container that satisfy a particular predicate,
1)for vector, string or deque, use erase-remove. 2) for a list, use
remove_if, 3) for associative container, write loop being sure to
postincrement your iterator. detail can be sen in effective STL item 9;