zi紫夕云 2019-08-12 14:21 采纳率: 0%
浏览 529

c++中map容器逆序迭代器删除某一键值问题

it2是顺序迭代器,rit是逆序迭代器,想通过逆序迭代器删除某一值,逆序迭代器需要用到base()转为顺序迭代器删除,但是直接转后删除发现逆序判断5,结果删了6,发现base()后会错一位,用以下方式移位,为何方法二失败了

方法1:成功
it2 = (++rit).base();
rit++
testearse.erase(it2->first);
方法2:失败
it2 = rit.base();
it2--;
rit++;
testearse.erase(it2->first);

#include <math.h>
#include <iostream>
#include<string>
#include "map"
using namespace std;

struct CmpByKeyBig {
    bool operator()(const int& k1, const int& k2)const {
        return k1 < k2;
    }
};

int main() {
    map<double, int, CmpByKeyBig> testearse;

    for (int i = 11; i >0; i--){
        testearse[double(i)] = i;
        //testearse.insert(make_pair(i, i));
    }

    map<double, int>::reverse_iterator  ritaa = testearse.rend();
    map<double, int>::iterator it2;
    while (rit != testearse.rend())
    {
        if ( rit->second == 5.0){
            it2 = (++rit).base();
            printf("it2->firt=%f,it2->second%d\n", it2->first,it2->second);
            rit++;
            testearse.erase(it2->first);
            continue;
        }
        rit++;
    }


    return 0;

    如果将while循环改为以下方式就无法运行
    {
        if ( rit->second == 4.0){
            it2 = rit.base();
            printf("it2->firt=%f,it2->second%d\n", it2->first,it2->second);
            rit++;
            it2--;
            testearse.erase(it2->first);
            continue;
        }
        rit++;
    }
  • 写回答

1条回答 默认 最新

  • zqbnqsdsmd 2019-08-13 00:09
    关注
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料