在c++ std::map上面用迭代器移除元素
·
在c++编程的时候,我们有时会遇到,在遍历map的时候,删除符合某个条件的元素,如果我们不做任何处理,直接删除map元素的话,程序会异常终端,提示"Expression: map/set iterator not incrementable"。所以如果想在遍历map的时候删除元素,必须做一些处理,下面给出一种方法.
原文参考:http://blog.chinaunix.net/uid-25808509-id-3339372.html
#include "stdafx.h"
#include "iostream"
using namespace std;
#include "map"
int main()
{
map<int, int> test_map;
test_map[1] = 1;
test_map[2] = 2;
test_map[3] = 3;
test_map[4] = 4;
for( std::map<int, int>::iterator iter = test_map.begin();
iter != test_map.end(); ++ iter )
{
cout << iter->first << " " << iter->second << endl;
}
int count = 0;
for( std::map<int, int>::iterator iter = test_map.begin(); iter != test_map.end();)
{
if( iter->first % 2 == 0)
{
test_map.erase(iter++);
}
else
{
iter++;
}
}
cout << "use count:" << count << endl;
cout << "after delete " << endl;
for( std::map<int, int>::iterator iter = test_map.begin();
iter != test_map.end(); ++ iter)
{
cout << iter->first << " " << iter->second << endl;
}
return 0;
}
更多推荐
所有评论(0)