【问题标题】:Can I continue to use an iterator after an item has been deleted from std::multimap<>? [duplicate]从 std::multimap<> 中删除项目后,我可以继续使用迭代器吗? [复制]
【发布时间】:2010-10-01 13:34:13
【问题描述】:

即使在调用 multimap::erase() 之后,我还能继续使用多映射迭代器吗?例如:

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 这样的参考网站在迭代器的生命周期或构造/破坏方法对迭代器的影响这个话题上出奇地安静。

【问题讨论】:

  • “出奇的安静”喜欢它!

标签: c++ stl multimap


【解决方案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.

所以它应该是这样的:

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

【讨论】:

  • 很抱歉向您提问,但迭代器的后增量不会导致现在已失效的迭代器的增量?我在第 7-9 行看到了您的注释块,但必须承认我不知道这一点。
  • 尽可能多的问题:-)
  • 来自标准草案 (n2521) 第 5.2.6 节:增量和减量。后缀 ++ 表达式的值是其操作数的值。 [注:得到的值是原值的副本——尾注]
  • 请注意,方法/函数的所有参数必须在调用方法/函数之前进行全面评估。所以上面的工作。
【解决方案2】:

C++ 标准 23.1.2.8:

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

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

【讨论】:

  • 你注意到iter++在 iter已经失效之后被调用了吗?您确定标准明确允许这样做吗?
  • 当然不是。标准保证,除了指向已擦除元素的迭代器之外的所有迭代器都是正确的。
  • 在这种情况下,直接回答 OPs 问题可能会为您赢得更多代表...
猜你喜欢
  • 2018-01-26
  • 2019-03-10
  • 2023-03-05
  • 2013-10-05
  • 1970-01-01
  • 2019-12-01
  • 2010-10-10
相关资源
最近更新 更多