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.

所以它应该是这样的:

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.
    }
}

另请参阅: 如果在从头到尾迭代时在地图元素上调用 erase() 会发生什么?

删除地图中的特定条目,但迭代器必须指向删除后的下一个元素

于 2009-01-15T10:34:23.143 回答
1

C++ 标准 23.1.2.8:

插入成员不应影响迭代器和对容器的引用的有效性,而擦除成员应仅使迭代器和对被擦除元素的引用无效。

这是所有关联容器的共同要求,std::multimap 就是其中之一。

于 2009-01-15T10:03:40.007 回答