2

multimap::erase() を呼び出した後でも multimap イテレータを使用し続けることはできますか? 例えば:

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

これは正しく実行されるはずですか、それとも消去の呼び出しに続いてイテレータが無効になりますか? http://www.cplusplus.com/reference/stl/multimap/erase.htmlのような参照サイトは、イテレータの寿命、またはイテレータに対する建設的/破壊的メソッドの影響に関するこのトピックについて奇妙に静かです。

4

2 に答える 2

17

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

于 2009-01-15T10:34:23.143 に答える
1

C++ 標準 23.1.2.8:

挿入メンバーは反復子とコンテナーへの参照の有効性に影響を与えず、消去メンバーは反復子と消去された要素への参照のみを無効にします。

これは、すべての連想コンテナーに共通の要件であり、std::multimap はその 1 つです。

于 2009-01-15T10:03:40.007 に答える