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

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

问题描述

出错代码(截取部分):

listint,int>> cachelist;
unordered_map<int,listint,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 '

分析与解决

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

参考链接

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

你可能感兴趣的:(C++)