C++ Unordered Map

133 views Asked by At

I have a program in which I am using an iterator to get access to a value of a map entry .

#include <iostream>
#include <cstdio>
#include <unordered_map>
#include <utility>
#include <algorithm>

using namespace std;

int main()
{
   int a[]={1,2,4,7,9,3,3,55,66,88,11};
   int k = 58;
   unordered_map<int,int> c;
   int i=0;
   for(auto x: a)
   {
       c.insert(make_pair(x,i));
       i++;
   }

   for(auto x: c)
   {
     if(c.count(k-x.first)==1) printf("%d %d\n",x.second,(c.find(k-x))->second);
   }

}

In the line:

if(c.count(k-x.first)==1) printf("%d %d\n",x.second,(c.find(k-x))->second);

I am getting errors especially in c.find()->second. I think it is the way to access elements from the iterator. What is wrong?

1

There are 1 answers

1
Cory Kramer On BEST ANSWER

You cannot say

c.find(k-x)

Because k is an int and x is a std::pair<int, int>. Do you mean one of these two?

c.find(k - x.first)

Or

c.find(k - x.second)

As a side note, it is generally unsafe to directly derefernce the returned iterator from find because if find returns .end() (as in, it didn't find an element with that key) then you've got a problem.