Can I continue to use an iterator after an item has been deleted from std::multimap<>? [duplicate]

StackOverflow https://stackoverflow.com/questions/446205

  •  22-07-2019
  •  | 
  •  

Question

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.

Was it helpful?

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

OTHER TIPS

C++ Standard 23.1.2.8:

The insert members shall not affect the validity of iterators and references to the container, and the erase members shall invalidate only iterators and references to the erased elements.

This is a common requirement for all associative containers, and std::multimap is one of them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top