-1

The following code doesn't compile. The line with pair is giving the error. Is there some other way to access the data or is this way correct??

unordered_map<int,int> hm;
unordered_map<int,int>::iterator it;
it=find(hm.begin(),hm.end(),x+c);
if (it!=hm.end())
{
  bNotFound = false;
  pair<int,int> p = *it;
  ind = p.second;
}
  • Can you make a full example out of your snippet? With `#include ...`, `int main()` and all the variable declarations and post the exact error message you got? – mch Jan 13 '22 at 11:46
  • 1
    Please be more specific than "not working". – molbdnilo Jan 13 '22 at 11:48
  • This question's shown code fails to meet Stackoverflow's requirements for showing a [mre]. Because of that it's unlikely that anyone here can conclusively answer the question; but only guess at the most. You need to [edit] your question to show a minimal example, no more than one or two pages of code (the "minimal" part), that everyone else can cut/paste ***exactly as shown***, compile, run, and reproduce the described issue (the "reproducible" part, this includes any ancillary information, like any input to the program). See [ask] for more information. – Sam Varshavchik Jan 13 '22 at 12:06
  • It's "not working" because it is missing the `#include` directives, and is attempting to execute statements outside of a function, and uses variables that have not been declared or defined. – Eljay Jan 13 '22 at 12:17

1 Answers1

0

Sometimes the compiler does a lousy job with the error messages. Your problem is the find algorithm.

unordered_map & map have their own find, which take the key as argument and returns an iterator. The algorithm is looking for the key:

  auto it = hm.find(key);
  if (it != hm.end())
  {
    // ...
  }

The global find algorithm takes a search interval and a value as input. But it works with any container that meets some iterators constrains. In the case of a map the value is not the key, as in the unordered_map::find but the (key, value) pair. The algorithm is looking for the (key, value) pair. You can declare your target value and use it like this:

  unordered_map<int, int>::value_type target{ key, value };
  auto it = find(hm.begin(), hm.end(), target);
  if (it != hm.end())
  {
    // ...
  }
zdf
  • 4,382
  • 3
  • 18
  • 29