1

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes I did that in count , forgot in find. Thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.