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

Logo

一站式虚拟内容创作平台,激发创意,赋能创作,进入R空间,遇见同道,让优质作品闪耀发光。​

更多推荐