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;
}
}
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
.
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.