正确运用stl map的erase方法
2010-04-12 23:53
507 查看
原文地址:http://my.donews.com/wucr/2007/07/01/post-070701-172017-974/ and http://www.sofee.cn/blog/2007/11/14/128/
STL的map表里有一个erase方法用来从一个map中删除掉指令的节点
eg:
像上面这样只是删除单个节点,map的形为不会出现任务问题,
但是当在一个循环里用的时候,往往会被误用,那是因为使用者没有正确理解iterator的概念.
像下面这样的一个例子就是错误的写法,
eg.
可以用以下方法解决这问题:
正确的写法
1.使用删除之前的迭代器定位下一个元素。STL建议的使用方式
/////////////////////////////////////////////////////////////////////////////////////////////
根据STL std::map中的定义void erase(iterator pos),此erase并不返回下一个元素的迭代器,因此不能采用std::list的方法
The truth is that ‘erase’ in associative containers doesn’t invalidate any iterators except those that point to elements being erased (that’s also true for ’sid::list’). For this reason, you don’t really need ‘map::erase’ to return an iterator. Just do this.
STL的map表里有一个erase方法用来从一个map中删除掉指令的节点
eg:
map<string,string> mapTest; typedef map<string,string>::iterator ITER; ITER iter=mapTest.find(key); mapTest.erase(iter);
像上面这样只是删除单个节点,map的形为不会出现任务问题,
但是当在一个循环里用的时候,往往会被误用,那是因为使用者没有正确理解iterator的概念.
像下面这样的一个例子就是错误的写法,
eg.
for(ITER iter = mapTest.begin(); iter != mapTest.end(); ++iter) { cout<< iter->first << ":" << iter->second << endl; mapTest.erase(iter); }这是一种错误的写法,会导致程序行为不可知.究其原因是map 是关联容器,对于关联容器来说,如果某一个元素已经被删除,那么其对应的迭代器就失效了,不应该再被使用;否则会导致程序无定义的行为。
可以用以下方法解决这问题:
正确的写法
1.使用删除之前的迭代器定位下一个元素。STL建议的使用方式
for(ITER iter = mapTest.begin(); iter != mapTest.end(); ) { cout<< iter->first << ":" << iter->second <<endl; mapTest.erase(iter++); }2. erase() 成员函数返回下一个元素的迭代器
for(ITER iter = mapTest.begin(); iter != mapTest.end();) { cout<< iter->first << ":" << iter->second <<endl; iter = mapTest.erase(iter); }
/////////////////////////////////////////////////////////////////////////////////////////////
根据STL std::map中的定义void erase(iterator pos),此erase并不返回下一个元素的迭代器,因此不能采用std::list的方法
The truth is that ‘erase’ in associative containers doesn’t invalidate any iterators except those that point to elements being erased (that’s also true for ’sid::list’). For this reason, you don’t really need ‘map::erase’ to return an iterator. Just do this.
for(iter = map.begin(); iter != map.end();) { if (shouldDelete(*iter)) map.erase(iter++); else ++iter; }
相关文章推荐
- 正确运用stl map的erase方法(转)
- 正确运用stl map的erase方法
- 正确运用stl map的erase方法
- 正确运用stl map的erase方法
- 正确运用stl map的erase方法
- 正确使用stl map的erase方法
- 正确使用stl map的erase方法
- 正确使用stl map的erase方法
- 正确使用stl map的erase方法
- 正确使用stl map的erase方法
- 正确使用stl map的erase方法
- 正确使用stl map的erase方法(转)
- 正确使用stl map的erase方法
- 正确使用stl map的erase方法
- 正确使用stl map的erase方法
- 正确使用stl map的erase方法
- 正确使用stl map的erase方法
- stl.list正确erase方法
- erase方法的正确使用
- 迭代器 stl map erase iterator 正确用法