-2

I am using std::unordered_map with custom classes as shown below. I have correctly initialised and set up the hasher function. What I want to know is how to use the find function and what will it return? I am confused as the reference doc says that for the unordered_map the value acts as the key.

SO was wondering what the iterator would point to in the case of below find function

class xyz {
public:
 int x;
 int y;
 int z;

//Required stuff
.
.
.
}

// Required Stuff
.
.
.

int main()
{
  std::unordered_map<class xyz, std::string, KeyHasher> dummy = {
    { {10, 11, 12}, "example"},
    { {2, 3, 21}, "another"}
  };
  std::unordered_map<xyz, std::string, keyHasher>::const_iterator got = dummy.find({2, 3, 21});

  //What will find return here? Is it the pointer to string "another"?

}

I have referred the following for basic setup of the custom classes. C++ unordered_map using a custom class type as the key

http://www.cplusplus.com/reference/unordered_set/unordered_set/find/

Community
  • 1
  • 1

1 Answers1

0

Given fixed code such as:

std::unordered_map<xyz, std::string, keyHasher>::const_iterator got = dummy.find({2, 3, 21});

What will find return here? Is it the pointer to string "another"?

It's an iterator to the matching {key, value} std::pair.

  • You can check that the find found the key with got != dummy.end().

  • If-and-only-if found, you can access the value "another" using the notation got->second, or access the key again as got->first.

confused as the reference doc says that for the unordered_map the value acts as the key.

That's just wrong - the unordered_map does not use the value as the key... it associates the value with the key, such that the value can be looked up using the key as discussed above.

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
  • Thank You. About the second question, I misunderstood the reference doc. (http://www.cplusplus.com/reference/unordered_set/unordered_set/) I quote the info from the document " In an unordered_set, the value of an element is at the same time its key, that identifies it uniquely. " This line confused me :) thank you . –  Apr 21 '15 at 08:28
  • @nightfury: it is a bit of a weird thing to say, and can be misleading given a custom comparison or `operator<` on the `set` element type might effectively make something else the key - such as a subset of the value's state. Elements are only "uniquely identified" in the sense that if `!(a < b) && !(b < a)` they're considered equal for the purposes of the set. BTW, I recommend using cppreference.com over cplusplus.com - the latter is famously unreliable. – Tony Delroy Apr 21 '15 at 09:07