本文介绍了从std :: multimap<>删除项目后,我可以继续使用迭代器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使在调用multimap :: erase()之后,我仍可以继续使用多图迭代器吗?例如:

Can I continue to use an multimap iterator even after a call to multimap::erase()? For example:

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

应该期望它正确运行,还是迭代器在调用擦除后无效?参考站点,例如奇怪的是,在迭代器的使用寿命或构造/破坏方法对迭代器的影响这一话题上。

Should this be expected to run correctly, or is the iterator invalidated following the call to erase? Reference sites like http://www.cplusplus.com/reference/stl/multimap/erase.html are strangely quiet on this topic of the lifespans of iterators, or the effects of constructive/destructive methods on iterators.

推荐答案

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

另请参阅:

这篇关于从std :: multimap<>删除项目后,我可以继续使用迭代器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 10:26