Junior — Middle
What properties should a class have to be used as a unique identifier or key in collections?
sobes.tech AI
Answer from AI
To use a class instance as a unique identifier or key in collections (for example, in std::unordered_map or std::map), the class must provide:
- Equality comparison operator (
operator==) — to check if two objects are equal. - Order comparison operator (
operator<) — if usingstd::mapor other ordered containers. - Hash function — if using
std::unordered_maporstd::unordered_set. You can specialize thestd::hashtemplate for your class.
Example for use in std::unordered_map:
#include <string>
#include <unordered_map>
class MyKey {
public:
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);
}
};
}
int main() {
std::unordered_map<MyKey, int> map;
map[{1, "test"}] = 42;
}
Thus, the class must be comparable and have a correct hash for use as a key.