Middle
What needs to be done to use a class as a key in an unordered_map?
sobes.tech AI
Answer from AI
To use a custom class as a key in std::unordered_map, you need to:
- Overload the equality comparison operator (
operator==) for your class.unordered_mapuses it to determine key equality. - Provide a hash function for your class. This can be done in one of the following ways:
- Specialize the template struct
std::hashfor your class. - Pass a hash functor object as the third argument to the
std::unordered_mapconstructor.
- Specialize the template struct
Example of specializing std::hash:
#include <functional>
struct MyClass {
int id;
std::string name;
// operator== required
bool operator==(const MyClass& other) const {
return id == other.id && name == other.name;
}
};
// Specialization of std::hash for MyClass
namespace std {
template <>
struct hash<MyClass> {
size_t operator()(const MyClass& obj) const {
// Combine hashes of members
return std::hash<int>()(obj.id) ^ (std::hash<std::string>()(obj.name) << 1);
}
};
}
Example of passing a hash functor to the constructor:
#include <functional>
#include <unordered_map>
struct MyClass {
int id;
std::string name;
bool operator==(const MyClass& other) const {
return id == other.id && name == other.name;
}
};
struct MyClassHasher {
size_t operator()(const MyClass& obj) const {
return std::hash<int>()(obj.id) ^ (std::hash<std::string>()(obj.name) << 1);
}
};
// Usage
std::unordered_map<MyClass, int, MyClassHasher> myMap;
It is important that the hash function is deterministic (always returns the same hash for the same object) and provides good distribution of hashes to minimize collisions.