Junior — Middle
What conditions must be met to use an object as a key in an unordered_set container?
sobes.tech AI
Answer from AI
To use an object as a key for an unordered_set container in C++, the following conditions must be met:
-
Define a hash function for this type. By default,
unordered_setusesstd::hash<T>. If there is no specialization ofstd::hashfor your type, you need to write one or provide your own hash function. -
Define an equality operator (
operator==) for your type, asunordered_setuses it to check for key equality.
Example:
struct MyKey {
int id;
std::string name;
bool operator==(const MyKey& other) const {
return id == other.id && name == other.name;
}
};
namespace std {
template<>
struct hash<MyKey> {
size_t operator()(const MyKey& k) const {
return hash<int>()(k.id) ^ (hash<std::string>()(k.name) << 1);
}
};
}
std::unordered_set<MyKey> mySet;
Thus, the object must be hashable and comparable for equality.