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>'
分析与解决
- 首先
unordered_map
的erase()
函数的参数可以是键值,可以是迭代器,也可以是迭代器区间,那么肯定不是erase()
的问题; - 然后报错提示告诉我们
pair<int,int>
不能用->
符号,那就奇怪了,位置①我们不是也用了it->second->second
吗?①处的it
是unordered_map
的iterator
,it->second
是list<pair<int,int>>
的iterator
,所以it->second->second
是pair
的第二值,好像没什么不对?? - 到这里可能你跟我一样,发现问题了,②处的
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