zoukankan      html  css  js  c++  java
  • C++ STL遍历map的时候如何删除其中的element

    我们通过map的erase(iterator it)方法删除元素的时候,如果此时erase处于遍历map的代码中,那么调用erase就需要小心一些。因为erase会导致输入参数iterator变的无效,从而影响后续的it++遍历map的逻辑。

    简单做法是,先将要删除的it保存下来,然后将用于遍历map的it指向下一个位置,然后删除掉保存下来的it。如下面代码所示:

    #include <map>
    #include <iostream>
    using namespace std;

    int main()
    {
        map<intint> map1;
        map<intint>::iterator mapit;
        map<intint>::iterator saveit;

        map1[1] = 2;
        map1[2] = 3;
        map1[3] = 4;
        map1[4] = 5;

        mapit = map1.begin();
        while (mapit != map1.end()) {
            cout << "Element key: " << mapit->first << ", value: " << mapit->second << endl;
            if (mapit->first == 2) {
                saveit = mapit;
                mapit++;
                map1.erase(saveit);
                continue;
            }
            mapit++;
        }

        cout << "Map size: " << map1.size() << endl;
        return 0;
    }

    需要注意的是,这里windows的STL(windows C++编译器带的STL)和linux上的STL(gcc的STL)实现不同。

    windows的STL中,map的erase方法会返回一个iterator,这个iterator指向的是当前被删除的iterator后面的iterator,所以这样的话,只需要将用于循环的iterator赋成erase函数的返回值就可以了。参考上面代码,就是这样:

    mapit = map1.erase(mapit);然后continue就可以。

    但是Linux下这样写代码是无法通过编译的。

  • 相关阅读:
    mit课程ocw-business
    2016中国人工智能企业TOP100, CBinsight2016年100家人工智能公司
    excel2013做数据透视表
    Mac OS X中,有三种方式来实现启动项的配置
    macbook双网卡路由
    怎么比较两个list中相同的值个数!
    创业圈必备英语
    全球最牛的100家AI创企:有多少独角兽?
    Java中字符串为什么不以结尾
    详解PPP模式下的产业投资基金运作【基金管理】
  • 原文地址:https://www.cnblogs.com/super119/p/2207541.html
Copyright © 2011-2022 走看看