c++如何遍历删除map/vector里面的元素
新技能Get!
问题
对于c++里面的容器, 我们可以使用iterator进行方便的遍历. 但是当我们通过iterator对vector/map等进行修改时, 我们就要小心了, 因为操作往往会导致iterator失效, 之后的行为都变得不可预知. 比如:
#include <iostream>
#include <vector> using namespace std; int main()
{
vector<int> a = {12, 23, 34, 45, 56, 67, 78, 89}; for (auto iter = a.begin(); iter != a.end(); ++iter) {
if (*iter > 30) {
a.erase(iter);
}
} for (const auto &element : a) {
cout<<element<<endl;
} return 0;
} 输出: 12
23
45
67
89
cplusplus的reference里对 std::vector::erase 的描述是:
Iterators, pointers and references pointing to position (or first) and beyond are invalidated, with all iterators, pointers and references to elements before position (or first) are guaranteed to keep referring to the same elements they were referring to before the call.
只有删除元素前面的iterator还保持有效, 之后的遍历行为不可预知.
解决方案
对于vector, erase会返回下一个iterator, 因此我们可以使用如下的方法:
#include <iostream>
#include <vector> using namespace std; int main()
{
vector<int> a = {12, 23, 34, 45, 56, 67, 78, 89}; auto iter = a.begin();
while (iter != a.end()) {
if (*iter > 30) {
iter = a.erase(iter);
}
else {
++iter;
}
} for (const auto &element : a) {
cout<<element<<endl;
} return 0;
} 输出: 12
23
对于map, 删除iterator只会影响当前的iterator, 因此使用for循环就够了, 比如:
#include <iostream>
#include <map> using namespace std; int main()
{
map<int, int> a = {{1, 12}, {2, 23}, {3, 34}, {4, 45}, {5, 56}, {6, 67}}; for (auto iter = a.begin(); iter != a.end(); ++iter) {
if (iter->second > 30) {
a.erase(iter);
}
} for (const auto &element : a) {
cout<<element.first<<" : "<<element.second<<endl;
} return 0;
} 输出: 1 : 12
2 : 23
但是更推荐的做法是在erase前让iterator指向下一个元素
#include <iostream>
#include <map> using namespace std; int main()
{
map<int, int> a = {{1, 12}, {2, 23}, {3, 34}, {4, 45}, {5, 56}, {6, 67}}; auto iter = a.begin();
while (iter != a.end()) {
if (iter->second > 30) {
a.erase(iter++);
}
else {
++iter;
}
} for (const auto &element : a) {
cout<<element.first<<" : "<<element.second<<endl;
} return 0;
} 输出: 1 : 12
2 : 23
参考资料
http://stackoverflow.com/questions/4645705/vector-erase-iterator
http://stackoverflow.com/questions/4600567/how-can-i-delete-elements-of-a-stdmap-with-an-iterator
c++如何遍历删除map/vector里面的元素的更多相关文章
- 【遍历集合】Java遍历List,Map,Vector,Set的几种方法
关于list,map,set的区别参考http://www.cnblogs.com/qlqwjy/p/7406573.html 1.遍历list @Test public void testList( ...
- 删除map、list集合元素总结
@Testpublic void removeElementFromMap(){Map<Integer, String> test = new HashMap<Integer, St ...
- Java 循环遍历删除set list中的元素
删除List和Set中的某些元素 错误代码的写法: Set<String> set = new HashSet<String>(); set.add("aaaaaa& ...
- map/vector遍历删除
map遍历删除 map<int, vector<int>>::iterator it = g_map.begin(); for (; it != g_map.end(); /* ...
- map,vector 等容器内容的循环删除问题(C++)
map,vector 等容器内容的循环删除问题(C++) map,vector等容器的循环删除不能用普通的方法删除: for(auto p=list.begin();p!=list.end();p++ ...
- Set,List,Map,Vector,ArrayList的区别(转)
JAVA的容器---List,Map,Set Collection ├List │├LinkedList │├ArrayList │└Vector │ └Stack └Set Map ├Hashtab ...
- STL容器的遍历删除
STL容器的遍历删除 今天在对截包程序的HashTable中加入计时机制时,碰到这个问题.对hash_map中的每个项加入时间后,用查询函数遍历hash_map,以删除掉那些在表存留时间比某个阈值长的 ...
- STL中用erase()方法遍历删除元素 .xml
pre{ line-height:1; color:#f0caa6; background-color:#2d161d; font-size:16px;}.sysFunc{color:#e54ae9; ...
- STL中用erase()方法遍历删除元素
STL中的容器按存储方式分为两类,一类是按以数组形式存储的容器(如:vector .deque):另一类是以不连续的节点形式存储的容器(如:list.set.map).在使用erase方法来删除元素时 ...
随机推荐
- sed命令手册
sed 是一种在线编辑器,它一次处理一行内容. 处理时,把当前处理的行存储在临时缓冲区中,称为“模式空间”(pattern space). 接着用sed命令处理缓冲区中的内容,处理完成后,把缓冲区的内 ...
- 使用阿里Docker镜像加速器加速
在阿里开发者平台注册开发者账号 https://dev.aliyun.com/search.html 注册之后可以访问Docker镜像服务 https://cr.console.aliyun.com/ ...
- C++中四种转换类型的区别
一.四种转换类型比较: 类型转换有c风格的,当然还有c++风格的.c风格的转换的格式很简单(TYPE)EXPRESSION,但是c风格的类型转换有不少的缺点,有的时候用c风格的转换是不合适的,因为它可 ...
- zzuliOJ 1904小火山的股票交易;
#include <stdio.h> #include <algorithm> #include <string.h> using namespace std; # ...
- 自定义ImageView回调实现手动改变圆环大小
//-----------------自定义MyView继承Imageview------------------------------- package com.bw.yuanhuan; impo ...
- jquery中prop()与attr()方法的区别
一.prop() 简单来说是当需要判断真假时使用,如复选框时: if( $(this).prop('checked')){ //当返回true时在这里调用 }else{ //当返回false时在这里调 ...
- JS倒计时网页自动跳转代码
<title>JS倒计时网页自动跳转代码</title> <script language="JavaScript" type="text/ ...
- c#开发Mongo笔记第二篇
写到第二篇不得不说是我之前犯了一个小错误,其实实现子表存储也是很简单的事,先说我想实现什么样的效果吧 就是用户表里有个成绩字段,成绩字段是个子表 其实实现这个功能也很简单,用面向对象的思想很好理解,子 ...
- 关于使用tracert命令检测网络问题
tracert命令是一个电脑网络工具-Windows命令行界面程序和内建命令,运行该命令后可以显示本机IP到达目标IP所经过的路由器IP地址,和响应的延迟信息! 在windows操作系统中,点击“开始 ...
- stringgrid事件大全
3.StringGrid之Event事件 property LiveBinding //把对象之间的属性绑定起来(XE2新增功能) property OnApplyStyleLookup: TNo ...