简体   繁体   English

在访问 c++ 中的 map 中的第一个和第二个对时出现编译器错误

[英]compiler error in accessing first and second of pair inside a map in c++

What is the problem in line of code inside inner for loop if else block??如果 else 阻塞,内部 for 循环内的代码行有什么问题? Accessing first and second of a pair inside a map is creating problems在 map 中访问一对中的第一个和第二个会产生问题

#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, pair<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;

    }
}

在此处输入图像描述

These are the errors I get:这些是我得到的错误:

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, std::pair<int, int> >::operator[](num).std::pair<int, int>::second', which is of non-class type 'int'


16:21: error: request for member 'second' in 'p.std::unordered_map<int, std::pair<int, int> >::operator[](num).std::pair<int, int>::second', which is of non-class type 'int'

I think you're mixing up between iterating on a hashtable, and accessing its value with a provided key.我认为您在迭代哈希表和使用提供的键访问其值之间混淆了。

In your first loop, to acess the pair <int, int> value, you just do p[num].first (first int of the pair ) or p[num].second .在您的第一个循环中,要访问pair <int, int>值,您只需执行p[num].first (first int of the pair ) 或p[num].second

It's not like your iterator loop, where it->first points to the key, and it->second.first & it->second.second points to the pair value.它不像您的迭代器循环,其中it->first指向键, it->second.first & it->second.second指向对值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM