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?
You cannot say
Because
k
is anint
andx
is astd::pair<int, int>
. Do you mean one of these two?Or
As a side note, it is generally unsafe to directly derefernce the returned iterator from
find
because iffind
returns.end()
(as in, it didn't find an element with that key) then you've got a problem.