zoukankan      html  css  js  c++  java
  • c++ 遍历map的时候删除元素

    1.#include <iostream>
    1.#include <map>
    2.using namespace std;
    3.
    4.
    5.int main()
    6.{
    7.    map<int, int> test_map;
    8.    test_map[1] = 1;
    9.    test_map[2] = 2;
    10.    test_map[3] = 3;
    11.    test_map[4] = 4;
    12.    
    13.    for( std::map<int, int>::iterator iter = test_map.begin();
    14.        iter != test_map.end(); ++ iter )
    15.    {
    16.        cout << iter->first << " " << iter->second << endl;
    17.    }
    18.    
    19.    int count = 0;
    20.    
    21.    // delete the element
    22.    for( std::map<int, int>::iterator iter = test_map.begin();
    23.        iter != test_map.end(); )
    24.    {
    25.        std::map<int, int>::iterator it_back = iter;
    26.        bool is_first_element = false;
    27.        if(it_back != test_map.begin())
    28.        it_back --;
    29.        else
    30.        is_first_element = true;
    31.        
    32.        // delete the element that matches the specific condition
    33.        if( iter->first % 2 == 0)
    34.        {
    35.            test_map.erase(iter);
    36.            
    37.            if(is_first_element)
    38.             iter = test_map.begin();
    39.            else
    40.                iter = ++ it_back;
    41.        }else iter ++;      
    42.        
    43.        count ++;
    44.    }
    45.    
    46.    cout << "use count:" << count << endl;
     
    48.    cout << "after delete " << endl;
    49.    
    50.    for( std::map<int, int>::iterator iter = test_map.begin();
    51.        iter != test_map.end(); ++ iter)
    52.    {
    53.        cout << iter->first << " " << iter->second << endl;
    54.    }
    55.    
    56.    system("pause");
    7.    return 0;
    58.     
    59.}
    
    运行结果
    1 1
    2 2
    3 3
    4 4
    use count:4
    after delete
    1 1
    3 3
  • 相关阅读:
    SQL Server 和Oracle 12C体系结构图
    SQL Server Latch
    MSSQL SSIS agent job运行出错
    sys.processes spid 和 blocked是同一个 session id
    黑苹果导致Windows时间不对或关机不断电
    MSSQL shrink数据库
    MSSQL 死锁或阻塞检测
    MSSQL不能shrink日志
    tomcat配置https协议
    ELK windows下部署测试
  • 原文地址:https://www.cnblogs.com/yangxx-1990/p/5142825.html
Copyright © 2011-2022 走看看