我可以继续使用一个迭代过后,项目已被删除,从std::基于<>?[重复]
题
这个问题已经有一个答案在这里:
我可以继续使用一个基于迭代,即使后一种调用的基于::删除()?例如:
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.
}
}
也参见:会发生什么,如果你叫删除()地图上的元素,同时循环,从开始到结束的?
和
其他提示
C++标准23.1.2.8:
插入成员不应影响的有效性和迭代引用的容器,并消除会员国应 无效只迭代和参考文献来被删除的要素。
这是一个共同要求所有缔容器,以及std::基于是他们中的一个。
不隶属于 StackOverflow