Can I continue to use the iterator after deleting an element from std :: multimap <>?

Can I continue to use the multicast iterator even after calling multimap :: erase ()? For instance:

 Blah::iterator iter; for ( iter = mm.begin(); iter != mm.end(); iter ++ ) { if ( iter->second == something ) { mm.erase( iter ); } } 

Should this be expected to work correctly, or is the iterator invalid after being called for deletion? Reference sites, such as http://www.cplusplus.com/reference/stl/multimap/erase.html , are strangely calm on this topic of iterator life cycles or the effects of constructive / destructive methods on iterators.

+3
source share
2 answers

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, iterating from start to finish?

and

delete a specific entry on the map, but the iterator should point to the next element after deletion

+18
source

C ++ Standard 23.1.2.8:

Insert members should not affect the validity of iterators and container references, and erase members should only invalidate iterators and references to erased elements.

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

+1
source

All Articles