c++ - 从 std::multimap<> 中删除项目后,我可以继续使用迭代器吗?

标签 c++ stl multimap

<分区>

我可以在调用 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在迭代器的生命周期或构造性/破坏性方法对迭代器的影响这个话题上出奇地安静。

最佳答案

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

关于c++ - 从 std::multimap<> 中删除项目后,我可以继续使用迭代器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/446205/

相关文章:

c++ - C++ 标准是否为编译器指定了 STL 实现细节?

java - 如何获取 MultiMap 值中元素的索引

c# - 差异 b/n 对象、引用、指针

c++ - 从可变参数模板中解压参数

c++ - 在 std::vector 构造函数中使用 std::string 数据类型

c++ - 重载赋值运算符导致递归警告

java - 双向多图等效数据结构

c++ - 获取 std::string 字符串的大小(以字节为单位)

c++ - 组合 ECDSA key

c++ - 在流中的下一行之后定位迭代器的最简单方法?