zoukankan      html  css  js  c++  java
  • 遍历list或map时删除元素(较巧妙)

    #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


  • 相关阅读:
    C语言实现快排
    C语言实现双向循环链表
    mysql插入数据后返回自增ID的方法
    golang flag包简单例子
    练习题 (六)
    练习题 (五)
    练习题 (四)
    练习题 (三)
    练习题 (二)
    练习题 (一)
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13318635.html
Copyright © 2011-2022 走看看