MiddleCodeCommonNot answered yet
How do you write a custom hash function for a user-defined key in unordered_map?
You have a user-defined key type Point { int x; int y; } and want to use it as the key in a std::unordered_map.
Constraints:
- Hash all fields (not just one) and combine them properly — a trivial XOR collides badly.
- The hash must be consistent with equality: equal keys must hash equal.
- Make the type usable in
unordered_mapwithout passing a hash explicitly.
struct Point { int x; int y; };
bool operator==(const Point& a, const Point& b);
namespace std {
template <>
struct hash<Point> {
std::size_t operator()(const Point& p) const noexcept {
// your code here
}
};
}
Write the implementation.
Specialise std::hash<MyKey> in namespace std, or pass a hash callable as the second template argument. Combine fields with hash_combine (not trivial XOR) and provide a consistent operator==.
- ✗Hashing only one field of a struct — high collision rate
- ✗Forgetting to keep
operator==consistent with the hash (equal keys must hash equal) - ✗Specialising
std::hashinside a different namespace — silently won't be found
- →What is
std::hash<std::string>typically based on (siphash, fnv, etc.)? - →How do you build a transparent hash to support heterogeneous lookup with
string_view?