C++ : 出错解释 base operand of '->' has non-pointer type 'std::pair<int, int>'

C++ ERROR : base operand of ‘->’ has non-pointer type ‘std::pair< int, int>’ 的解释

问题描述

出错代码(截取部分):
list<pair<int,int>> cachelist;
unordered_map<int,list<pair<int,int>>::iterator> map;

void put(int key, int value) {
    auto it = map.find(key);
    if(it != map.end()){
        touch(it->second);
        it->second->second = value; // ①
    }
    else if(map.size() < cap){
        cachelist.push_front(make_pair(key,value));
        map[key]=cachelist.begin();
    }
    else{
        auto it = cachelist.back();// ②
        map.erase(it->first); // 出错位置~~!!
        cachelist.pop_back();
        cachelist.push_front(make_pair(key,value));
        map[key]=cachelist.begin();
    }
}
报错内容:

Line xx: base operand of '->' has non-pointer type ' std::pair <int, int>'

分析与解决

  1. 首先unordered_maperase() 函数的参数可以是键值,可以是迭代器,也可以是迭代器区间,那么肯定不是erase()的问题;
  2. 然后报错提示告诉我们pair<int,int>不能用->符号,那就奇怪了,位置①我们不是也用了it->second->second吗?①处的itunordered_mapiteratorit->secondlist<pair<int,int>>iterator,所以it->second->secondpair的第二值,好像没什么不对??
  3. 到这里可能你跟我一样,发现问题了,②处的it并不是list<pair<int,int>>的迭代器,而是cachelist的最后一个元素节点的地址,auto实际上应该是pair<int,int> &,而pair<int,int>是不认识->符号的,所以出错位置的应该把->改成.,即:
map.erase(it.first);

参考链接

http://stackoverflow.com/questions/21058894/error-base-operand-of-has-non-pointer-type-stdpairint-int

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值