加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

vector list map 遍历删除制定元素 防止迭代器失效的实例

发布时间:2020-12-16 05:15:45 所属栏目:百科 来源:网络整理
导读:方法如下所示: // k_control.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "stdio.h" #include vector #include map #include string #include list using namespace std; int _tmain(int argc,_TCHAR* argv[]) { printf("run main

方法如下所示:

// k_control.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "stdio.h"
#include <vector>
#include <map>
#include <string>
#include <list>
using namespace std;
int _tmain(int argc,_TCHAR* argv[])
{
printf("run main");
vector<int> vect ;
vect.push_back(1);
vect.push_back(2);
vect.push_back(3);
vect.push_back(4);
vect.push_back(5);

vector<int>::iterator iter = vect.begin();
for(iter;iter!=vect.end();){
if(*iter == 3){
iter=vect.erase(iter);
}else{
iter++;
}
}
map<int,string> map_local ;
map_local[1]="hello_1";
map_local[2]="hello_2";
map_local[3]="hello_3";
map_local[4]="hello_4";
map_local[5]="hello_5";
map<int,string>::iterator iter_map=map_local.begin();
for(iter_map;iter_map!=map_local.end();){
if(iter_map->first==1){
map_local.erase(iter_map++);
或者
//iter_map=map_local.erase(iter_map);
}else{
iter_map++;
}

}


list<int> list_my;
list_my.push_back(1);
list_my.push_back(2);
list_my.push_back(3);
list_my.push_back(4);
list_my.push_back(5);
list<int>::iterator iter_list = list_my.begin();
for(iter_list;iter_list!=list_my.end();){
if(*iter_list==2){
list_my.erase(iter_list++);
或者
//iter_list=list_my.erase(iter_list);
}else
iter_list++;
}


printf("run over");
return 0;
}

以上就是小编为大家带来的vector list map 遍历删除制定元素 防止迭代器失效的实例全部内容了,希望大家多多支持编程小技巧~

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读