Can I continue to use an iterator after an item has been deleted from std::multimap<>?
c++, multimap, stl
Solution
http://www.sgi.com/tech/stl/Multimap.html
Multimap has the important property that inserting a new element
into a multimap does not invalidate iterators that point to existing
elements. Erasing an element from a multimap also does not invalidate
any iterators, except, of course, for iterators that actually point to
the element that is being erased.
So it should look like this:
Blah::iterator iter;
for ( iter = mm.begin();iter != mm.end();)
{
if ( iter->second == something )
{
mm.erase( iter++ );
// Use post increment. This increments the iterator but
// returns a copy of the original iterator to be used by
// the erase method
}
else
{
++iter; // Use Pre Increment for efficiency.
}
}
Also see: What happens if you call erase() on a map element while iterating from begin to end?
and
delete a specific entry in the map,but the iterator must point to the next element after the deletion
Problem
Can I continue to use an multimap iterator even after a call to multimap::erase()? For example: ``` Blah::iterator iter; for ( iter = mm.begin(); iter != mm.end(); iter ++ ) { if ( iter->second == something ) { mm.erase( iter ); } } ``` Should this be expected to run correctly, or is the iterator invalidated following the call to erase? Reference sites like http://www.cplusplus.com/reference/stl/multimap/erase.html are strangely quiet on this topic of the lifespans of iterators, or the effects of constructive/destructive methods on iterators.