Junior — Middle
How is the comparison of objects used as keys in std::unordered_map implemented?
sobes.tech AI
Answer from AI
In std::unordered_map, objects used as keys are compared using the equality function, which by default is std::equal_to<Key>.
When inserting or searching for a key:
- The hash code of the key is computed using a hash function (by default std::hash<Key>).
- The corresponding bucket is searched using key comparison via the == operator or a specified equality predicate.
If the keys are user-defined types, it is necessary to:
- Define a specialization of std::hash for that type or provide your own hash function.
- Define the == operator or provide your own equality comparison function.
Example:
struct Key {
int id;
bool operator==(const Key& other) const {
return id == other.id;
}
};
namespace std {
template<>
struct hash<Key> {
size_t operator()(const Key& k) const {
return std::hash<int>()(k.id);
}
};
}
std::unordered_map<Key, std::string> map;