您的位置:首页 > 编程语言 > C语言/C++

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

2017-02-21 22:52 5836 查看

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ pair 出错