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

浪子不回头ぞ 提交于 2019-12-18 12:42:13

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/446205/can-i-continue-to-use-an-iterator-after-an-item-has-been-deleted-from-stdmulti

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!