Note 33.11.1.
Always remember that a hash function and equality operation for objects in a hash table always should be based on the same attributes.
unordered_set and unordered_map classes that implement hash table based sets and maps. (As opposed to the set and map classes that implement BST based sets and maps.)
std::unordered_set and std::unordered_map classes is that the key type must be hashable and comparable for equality.
std::hash for that type. Although normally you do not want to add things to the std namespace, specializing std::hash for a custom data type is an exception to that rule. The listing below shows this being done for a simple Person struct.
std::hash<Person>, on line 38, we can simply declare:
std::unordered_map<Person, string> personToCity;
std::hash<Person> to hash the keys and the equality operator to compare keys for equality when needed.
std::unordered_map. We can also pass in a functor that determines equality if we donβt want to use the default equality operator. This second version of the program uses this approach:
std::unordered_map<Person, string, PersonHash, PersonEqual> personToCity;
== used the same logic, we could skip the equality functor and just use the default equality operator. In that case, we could declare the unordered map like this:
std::unordered_map<Person, string, PersonHash> personToCity;