3

What is the problem in line of code inside inner for loop if else block?? Accessing first and second of a pair inside a map is creating problems

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

    }
}

enter image description here

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'
JHBonarius
  • 10,824
  • 3
  • 22
  • 41
Suyash_14
  • 43
  • 5
  • Can you be more specific about the problems please? Is there a compiler error, or the results are not as you expect? – BoBTFish Dec 21 '20 at 08:30
  • compiler error in accesing the first and second of pair inside the map @BoBTFish – Suyash_14 Dec 21 '20 at 08:32
  • please edit to put the compilation error /inside/ the question. – JHBonarius Dec 21 '20 at 08:34
  • 1
    `unordered_map> :: iterator it = p.begin(); for(;it != p.end();it++)` This is one reason we now have `auto` -> `for(auto it = p.begin();it != p.end();it++)` – JHBonarius Dec 21 '20 at 08:40
  • 1
    IMHO this example shows why it's not a good idea to use `std::pair`. If you get statements like `foo[i].first.second[j].second.first` you have no idea what's happening. Better to make your own struct `struct Foo{ int bar, baz; };`. – JHBonarius Dec 21 '20 at 08:54

1 Answers1

2

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.

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.

JHBonarius
  • 10,824
  • 3
  • 22
  • 41
DarthQuack
  • 1,254
  • 3
  • 12
  • 22