在c++编程的时候,我们有时会遇到,在遍历map的时候,删除符合某个条件的元素,如果我们不做任何处理,直接删除map元素的话,程序会异常终端,提示"Expression: map/set iterator not incrementable"。所以如果想在遍历map的时候删除元素,必须做一些处理,下面给出一种方法.
-
#include <iostream>
-
#include <map>
-
using namespace std;
-
-
-
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;
-
-
// delete the element
-
for( std::map<int, int>::iterator iter = test_map.begin();
-
iter != test_map.end(); )
-
{
-
std::map<int, int>::iterator it_back = iter;
-
bool is_first_element = false;
-
if(it_back != test_map.begin())
-
it_back --;
-
else
-
is_first_element = true;
-
-
// delete the element that matches the specific condition
-
if( iter->first % 2 == 0)
-
{
-
test_map.erase(iter);
-
-
if(is_first_element)
-
iter = test_map.begin();
-
else
-
iter = ++ it_back;
-
}else iter ++;
-
-
count ++;
-
}
-
-
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;
-
}
-
-
system("pause");
-
return 0;
-
-
}
运行结果
-
1 1
-
2 2
-
3 3
-
4 4
-
use count:4
-
after delete
-
1 1
-
3 3
遍历所需次数,也就是整个map的总元素个数,不会增加额外的次数
********************************************************************
2017.07.01 飘过
其实遍历map时候,删除元素很常见,也很简单
-
for( std::map<int, int>::iterator iter = test_map.begin(); iter != test_map.end(); ){
-
if( iter->first % 2 == 0){
-
iter = test_map.erase(iter);
-
}else iter++;
-
}
或者
-
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++;
-
}
阅读(26367) | 评论(0) | 转发(2) |