Design&Art

C++博客 首页 新随笔 联系 聚合 管理
  26 Posts :: 0 Stories :: 38 Comments :: 0 Trackbacks

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);
}
posted on 2009-01-22 13:33 安帛伟 阅读(26290) 评论(7)  编辑 收藏 引用 所属分类: STL

Feedback

# re: 正确使用stl map的erase方法 2010-05-24 14:19 啊啊
for(ITER iter=mapTest.begin();iter!=mapTest.end();)
{
cout<<iter->first<<":"<<iter->second<<endl;
iter=mapTest.erase(iter);
}

不对

http://www.cplusplus.com/reference/stl/map/erase/

返回删除元素的个数  回复  更多评论
  

# re: 正确使用stl map的erase方法 2011-05-30 11:13 过客
呵呵,文章虽好,但不要误导呀。  回复  更多评论
  

# re: 正确使用stl map的erase方法 2011-05-30 11:16 过客
说错话了。
刚找到问题所在,楼主说的WINDOWS版的。LINUX版有earase,但没有返回值是迭代器的earase方法。http://www.cppblog.com/bujiwu/archive/2009/11/01/99928.aspx?opt=admin  回复  更多评论
  

# re: 正确使用stl map的erase方法[未登录] 2012-07-06 11:56 ...
for(ITER iter=mapTest.begin();iter!=mapTest.end();)
{
cout<<iter->first<<":"<<iter->second<<endl;
mapTest.erase(iter++); // ???? 这样也行 ?? 只能用临时变量保存下一个迭代地址才行,这样肯定不可以
}  回复  更多评论
  

# re: 正确使用stl map的erase方法 2012-07-06 12:25 aa
@过客
说的很好嘛. 这种仅适用于windows的代码本就不该提倡.  回复  更多评论
  

# re: 正确使用stl map的erase方法[未登录] 2013-04-02 17:50 123
@啊啊
没有仔细看map用法,不要瞎评论。  回复  更多评论
  

# re: 正确使用stl map的erase方法 2014-04-22 14:04 blong
@啊啊
其实是c++98跟c++11标准里的区别
  回复  更多评论
  


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理