代码之家  ›  专栏  ›  技术社区  ›  Stéphane

从std::multimap<>中删除项目后,我可以继续使用迭代器吗?[副本]

  •  2
  • Stéphane  · 技术社区  · 17 年前

    即使调用了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 对于迭代器的寿命,或者构造性/破坏性方法对迭代器的影响,他们出奇地沉默。

    2 回复  |  直到 16 年前
        1
  •  17
  •   Community Mohan Dere    8 年前

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

    另请参见: What happens if you call erase() on a map element while iterating from begin to end?

    delete a specific entry in the map,but the iterator must point to the next element after the deletion

        2
  •  1
  •   Igor Semenov    17 年前

    C++标准23.1.2.8:

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

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

    推荐文章