C++ STL遍历map的时候如何删除其中的element
来源:互联网 发布:linux命令行创建文件 编辑:程序博客网 时间:2024/05/29 13:10
我们通过map的erase(iterator it)方法删除元素的时候,如果此时erase处于遍历map的代码中,那么调用erase就需要小心一些。因为erase会导致输入参数iterator变的无效,从而影响后续的it++遍历map的逻辑。
简单做法是,先将要删除的it保存下来,然后将用于遍历map的it指向下一个位置,然后删除掉保存下来的it。如下面代码所示:
#include <map>
#include <iostream>
using namespace std;
int main()
{
map<int, int> map1;
map<int, int>::iterator mapit;
map<int, int>::iterator saveit;
map1[1] = 2;
map1[2] = 3;
map1[3] = 4;
map1[4] = 5;
mapit = map1.begin();
while (mapit != map1.end()) {
cout << "Element key: " << mapit->first << ", value: " << mapit->second << endl;
if (mapit->first == 2) {
saveit = mapit;
mapit++;
map1.erase(saveit);
continue;
}
mapit++;
}
cout << "Map size: " << map1.size() << endl;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
map<int, int> map1;
map<int, int>::iterator mapit;
map<int, int>::iterator saveit;
map1[1] = 2;
map1[2] = 3;
map1[3] = 4;
map1[4] = 5;
mapit = map1.begin();
while (mapit != map1.end()) {
cout << "Element key: " << mapit->first << ", value: " << mapit->second << endl;
if (mapit->first == 2) {
saveit = mapit;
mapit++;
map1.erase(saveit);
continue;
}
mapit++;
}
cout << "Map size: " << map1.size() << endl;
return 0;
}
需要注意的是,这里windows的STL(windows C++编译器带的STL)和linux上的STL(gcc的STL)实现不同。
windows的STL中,map的erase方法会返回一个iterator,这个iterator指向的是当前被删除的iterator后面的iterator,所以这样的话,只需要将用于循环的iterator赋成erase函数的返回值就可以了。参考上面代码,就是这样:
mapit = map1.erase(mapit);然后continue就可以。
但是Linux下这样写代码是无法通过编译的。
- C++ STL 遍历 map 的时候如何删除其中的 element
- C++ STL遍历map的时候如何删除其中的element
- C++ STL 遍历 map 的时候如何删除其中的 element
- C++ STL遍历map的时候如何删除其中的element
- c++ 遍历map的时候删除元素
- 码农小汪-Map遍历的时候删除元素
- List遍历的时候将其中的元素删除掉
- stl map高效遍历删除的方法
- stl map高效遍历删除的方法
- stl map遍历和删除的方法
- stl map高效遍历删除的方法
- stl map遍历删除的方法
- c++ STL map的增加删除遍历操作
- C++ STL Map的创建、删除、插入、更新、遍历
- 遍历的时候删除List
- 遍历的时候删除List
- stl map vector的删除
- STL Vector 的遍历删除
- spring自动建表 很蛋疼的问题(exception)create update
- JS 定时器 (setInterval 和 setTimeout 函数)
- Linux下使用SFTP命令
- TKPROF工具
- 智能指针scoped_ptr组件的使用
- C++ STL遍历map的时候如何删除其中的element
- Spring 开发笔记之 java.sql.SQLException: Lock wait timeout exceeded | CannotAcquireLockException 的解决
- 运行时获取方法调用堆栈信息(java)
- c++ vector遍历删除元素 出错的问题
- Psapi.dll
- XEN 虚拟化
- 在家也能健身(03):肩三角肌
- 编程打断拆分构件
- kernel: cciss: fifo full