我是靠谱客的博主 听话音响,最近开发中收集的这篇文章主要介绍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下这样写代码是无法通过编译的。

转载于:https://www.cnblogs.com/super119/archive/2011/10/11/2207541.html

最后

以上就是听话音响为你收集整理的C++ STL遍历map的时候如何删除其中的element的全部内容,希望文章能够帮你解决C++ STL遍历map的时候如何删除其中的element所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(58)

评论列表共有 0 条评论

立即
投稿
返回
顶部