以下三段代码摘自《C++ 标准程序库》p204-205
代码段一:
- typedef std::map<std::string, float> StringFloatMap;
- StringFloatMap coll;
- StringFloatMap::iterator pos;
- //...
- for (pos = coll.begin(); pos != coll.end(); ++pos)
- {
- if (pos->second == value)
- {
- coll.erase(pos); // RUNTIME ERROR !!!
- }
- }
代码段 二:
- // 如果 erase() 总是返回下一元素的位置, 那就好办了,如下
- typedef std::map<std::string, float> StringFloatMap;
- StringFloatMap coll;
- StringFloatMap::iterator pos;
- //...
- for (pos = coll.begin(); pos != coll.end(); )
- {
- if (pos->second == value)
- {
- pos = coll.erase(pos); // would be fine, but COMPLILE TIME ERROR!!!
- }
- else
- {
- ++ pos;
- }
- }
代码段三: 完整且正确的哦
- #include <vector>
- #include <string>
- #include <iostream>
- #include <map>
- using namespace std;
- int _tmain(int argc, _TCHAR* argv[])
- {
- typedef map<string, int> StringIntMap;
- StringIntMap coll;
- coll.insert(make_pair("one", 1));
- coll.insert(make_pair("two", 2));
- coll.insert(make_pair("three", 3));
- coll.insert(make_pair("four", 4));
- {
- cout << "称除元素前: " << endl;
- StringIntMap::iterator itBeg = coll.begin();
- StringIntMap::iterator itEnd = coll.end();
- for (NULL; itBeg != itEnd; ++itBeg)
- {
- cout << itBeg->first << "---> " << itBeg->second << endl;
- }
- }
- { // 重点看这一段 ************************************************************
- // 移除值为"2" 的项
- StringIntMap::iterator itBeg = coll.begin();
- StringIntMap::iterator itEnd = coll.end();
- for (NULL; itBeg != itEnd; )
- {
- if (itBeg->second == 2)
- {
- coll.erase(itBeg ++ ); // 重点分析这一句:
- }
- else
- {
- ++itBeg;
- }
- }
- // 分析: 注意这一句相当于
- // 1.StringIntMap::iterator itTmp = itBeg;
- // 2. itBeg 自增.指向下一个元素
- // 3. coll.erase(itTmp); // 注意哦,调用erase后 迭代器无效, 但是这里是临时的对象,不怕....
- // 更详解决可看 标准库的源码,或者看类似的解释 http://blog.youkuaiyun.com/w_sx12553/article/details/8507188
- } // 重点看这一段 ************************************************************
- cout << endl << "称除元素后: " << endl;
- {
- StringIntMap::iterator itBeg = coll.begin();
- StringIntMap::iterator itEnd = coll.end();
- for (NULL; itBeg != itEnd; ++itBeg)
- {
- cout << itBeg->first << "---> " << itBeg->second << endl;
- }
- }
- return 0;
- }