即使在调用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这样的参考站点在迭代器的生命周期主题或者建设性/破坏性方法对迭代器的影响方面都非常安静.
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. } }
另请参阅: 如果在从开始到结束迭代时调用map元素上的erase()会发生什么?
和
删除映射中的特定条目,但迭代器必须指向删除后的下一个元素