正确使用stl map的erase方法
来源:互联网 发布:arp绑定mac 编辑:程序博客网 时间:2024/05/16 10:19
先声明:下面的文章是针对windows的用法,因为std::map的erase函数的windows的实现版本是返回一个std::map的迭代器,但是STL标准里面的该函数的返回值确是:
map.erase有3个重载:
void erase ( iterator position );
size_type erase ( const key_type& x );
void erase ( iterator first, iterator last );
。
所以下面的代码中的最后一个例子仅仅可以在windows下的map下运行。
STL的map表里有一个erase方法用来从一个map中删除掉指令的节点
eg1:
typedef map<string,string>::iterator ITER;
ITER iter=mapTest.find(key);
mapTest.erase(iter);
像上面这样只是删除单个节点,map的形为不会出现任务问题,
但是当在一个循环里用的时候,往往会被误用,那是因为使用者没有正确理解iterator的概念.
像下面这样的一个例子就是错误的写法,
eg2:
{
cout<<iter->first<<":"<<iter->second<<endl;
mapTest.erase(iter);
}
这是一种错误的写法,会导致程序行为不可知.究其原因是map 是关联容器,对于关联容器来说,如果某一个元素已经被删除,那么其对应的迭代器就失效了,不应该再被使用;否则会导致程序无定义的行为。
VS报错信息:map/set iterator not incrementable
可以用以下方法解决这问题:
正确的写法
1.使用删除之前的迭代器定位下一个元素。STL建议的使用方式
{
cout<<iter->first<<":"<<iter->second<<endl;
mapTest.erase(iter++);
}
2.erase() 成员函数返回下一个元素的迭代器
{
cout<<iter->first<<":"<<iter->second<<endl;
iter=mapTest.erase(iter);
}
int _tmain(int argc, _TCHAR* argv[])
{
map<int,int> mapTest;
typedef map<int,int>::iterator ITER;
typedef pair<int,int> Pair_Int;
for (int i=0; i<5; i++)
{
mapTest.insert(Pair_Int(i,i*i));
}
for(ITER iter=mapTest.begin();iter!=mapTest.end();++iter)
{
cout<<iter->first<<":"<<iter->second<<endl;
mapTest.erase(iter);
}
return 0;
}
运行结果:
for(ITER iter=mapTest.begin();iter!=mapTest.end(); )
{
cout<<iter->first<<":"<<iter->second<<endl;
iter = mapTest.erase(iter);
}
或改为:
for(ITER iter=mapTest.begin();iter!=mapTest.end(); )
{
cout<<iter->first<<":"<<iter->second<<endl;
mapTest.erase(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 map的erase方法(转)
- 使用ValidForm进行表单验证,结合SpringMVC检验用户名是否存在
- spring mvc 通过redirect重定向防止刷新页面重复提交又能返回数据给前台页面
- 两个数据交换的几种解法
- 预装APK的方法介绍
- 解决“arcsde服务启动又停止的问题”
- 正确使用stl map的erase方法
- js模版引擎。
- hdoj 1229 还是A+B 水过~
- JSF web页面的<h:inputTextarea>和数据库存储的回车换行及<br />问题
- HTTP 错误 404.2 - Not Found 由于 Web 服务器上的“ISAPI 和 CGI 限制”列表设置,无法提供您请求的页面
- hdu 1276 士兵队列训练问题
- JQuery总结
- Ice
- ubuntu下使用Eclipse搭建Hadoop开发环境