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 class as a key in std::unordered_map, you need to:
- Implement the
==operator to compare instances of your class for equality.unordered_mapuses it to check for the presence of a key. - Implement a hash function for your class.
unordered_mapuses it to compute the hash of the key and determine the bucket to place the element in. The standard library providesstd::hashfor basic types. For user-defined classes, you can either specialize thestd::hashtemplate or provide your own hash function and pass it as the third template argument tounordered_map.
Example:
#include <unordered_map>
#include <string>
#include <functional>
// User-defined class
struct MyKey {
int id;
std::string name;
// Overload the == operator
bool operator==(const MyKey& other) const {
return id == other.id && name == other.name;
}
};
// Specialize std::hash for MyKey
namespace std {
template <>
struct hash<MyKey>
{
std::size_t operator()(const MyKey& key) const
{
// Combine hashes of the fields
return std::hash<int>()(key.id) ^ (std::hash<std::string>()(key.name) << 1);
}
};
}
int main() {
// Using MyKey as a key
std::unordered_map<MyKey, int> myMap;
MyKey key1 = {1, "Test1"};
MyKey key2 = {2, "Test2"};
myMap[key1] = 10;
myMap[key2] = 20;
return 0;
}