Sobes.tech
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:

  1. Implement the == operator to compare instances of your class for equality. unordered_map uses it to check for the presence of a key.
  2. Implement a hash function for your class. unordered_map uses it to compute the hash of the key and determine the bucket to place the element in. The standard library provides std::hash for basic types. For user-defined classes, you can either specialize the std::hash template or provide your own hash function and pass it as the third template argument to unordered_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;
}