User-defined Types as Hash Keys in C++
User-defined types can not be used as keys in containers like std::unordered_map unless we provide some extra features to them.
First, we need to figure out what does hashmap do under the hood. There are two important features in hashmap structure.
- To find out where to put the key-value pairs in the hash table.
- How to tell if two keys are identical.
That’s exactly what we need to provide to our user-defined types to help hash map do its work easily. Basically, We need to implement these two:
- A equality operator.
- A hash function.
If we directly use struct Pointer as the key type in std::unordered_map, we will get tons of compile errors.
| 1 | struct Point { | 
To make the Point type hashable, we need to modify the code to be:
| 1 | struct Point { | 
| 1 | output: | 
User-defined Types as Hash Keys in C++
http://chuzcjoe.github.io/cpp/cpp-user-defined-types-as-hash-key/
