在 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;

    }
}

enter image description here

这些是我得到的错误

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].firstint 的第一个 pair)或 p[num].second。>

它不像您的迭代器循环,其中 it->first 指向键,而 it->second.first & it->second.second 指向对值。