遍历list或map时删除元素(较巧妙)

来源:互联网 发布:黑猫微圈源码 编辑:程序博客网 时间:2024/05/20 07:35
#include <iostream>#include <list>#include <map>using namespace std;int main(){     std::list<int> test_list;     test_list.push_back(1);     test_list.push_back(2);     test_list.push_back(3);     test_list.push_back(4);     test_list.push_back(5);     test_list.push_back(6);          cout << "*****************delete list***************" << endl;     std::list<int>::iterator iter = test_list.begin();     for(iter ; iter != test_list.end();)     {              if(*iter % 2 == 0)              {                      test_list.erase(iter++);             }else ++iter;    }        for(iter = test_list.begin(); iter != test_list.end(); ++ iter)    {              cout << *iter << " ";    }    cout << endl;        cout << "*****************delete map****************" << endl;    std::map<int, int> test_map;    test_map[1] = 1;    test_map[2] = 2;    test_map[3] = 3;    test_map[4] = 4;    test_map[5] = 5;    test_map[6] = 6;    std::map<int, int>::iterator t_iter = test_map.begin();    for(t_iter; t_iter != test_map.end(); )    {                 if(t_iter->second % 2 == 0)                 {                                  test_map.erase(t_iter++);                }else ++ t_iter;    }        for(t_iter = test_map.begin(); t_iter != test_map.end(); ++ t_iter)    {              cout << t_iter->second << " ";    }    cout << endl;        system("pause");    return 0;}比较巧妙的点就在于 test_list.erase(iter++); test_map.erase(t_iter++); 利用后置自增操作符,传给erase函数的iterator是指向当前元素,而在这条语句之后,iter 自增,从而指向下一个元素,而不会导致因当前iterator删除而不能正确访问下一个元素的问题。 运行结果 *****************delete list***************1 3 5*****************delete map****************1 3 5


原创粉丝点击