如何解决在 C++ 中访问映射中的第一对和第二对时的编译器错误
如果 else 块,内部 for 循环内的代码行有什么问题? 访问地图中的第一个和第二个会产生问题
#include <iostream>
#include <unordered_map>
#include <utility>
using namespace std;
int main() {
int t; cin>>t;
for(int i = 0; i < t; i++){
int n; cin>>n; int sum = 0;
unordered_map<int,pair<int,int>> p;
for(int i = 0; i < n; i++){
int num; cin>>num;
if( (p[num].second ).first == 0)
( (p[num]).second ).first = i;
else
( (p[num]).second ).second = i;
}
unordered_map<int,int>> :: iterator it = p.begin();
for(;it != p.end();it++){
int diff = abs(it->second.second - it->second.first);
sum = sum + diff;
}
cout<<sum<<endl;
}
}
这些是我得到的错误:
In function 'int main()':
13:21: error: request for member 'first' in 'p.std::unordered_map<int,std::pair<int,int> >::operator[](num).std::pair<int,int>::second',which is of non-class type 'int'
14:21: error: request for member 'first' in 'p.std::unordered_map<int,which is of non-class type 'int'
16:21: error: request for member 'second' in 'p.std::unordered_map<int,which is of non-class type 'int'
解决方法
我认为您在迭代哈希表和使用提供的键访问其值之间混淆了。
在您的第一个循环中,要访问 pair <int,int>
值,您只需执行 p[num].first
(int
的第一个 pair
)或 p[num].second
。>
它不像您的迭代器循环,其中 it->first
指向键,而 it->second.first
& it->second.second
指向对值。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。