Sobes.tech
Middle+

What needs to be done to use your class as a key in a map or unordered_map?

sobes.tech AI

Answer from AI

For std::map:

You need to define the comparison operator < for your class.

#include <map>
#include <string>

struct MyKey {
    int id;
    std::string name;

    // Define the "<" operator
    bool operator<(const MyKey& other) const {
        if (id != other.id) {
            return id < other.id;
        }
        return name < other.name;
    }
};

int main() {
    std::map<MyKey, int> myMap;
    MyKey key1{1, "apple"};
    MyKey key2{2, "banana"};
    myMap[key1] = 10;
    myMap[key2] = 20;
    return 0;
}

For std::unordered_map:

You need to define a hash function for your class and, if necessary, the equality operator ==. The standard hash std::hash does not support user-defined types.

Ways to define a hash:

  1. Overload std::hash in the std namespace (not recommended):

    #include <unordered_map>
    #include <string>
    #include <functional> // For std::hash
    
    struct MyKey {
        int id;
        std::string name;
    
        // Define 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> {
            size_t operator()(const MyKey& key) const {
                // Simple hash combination example
                // More complex and robust hash functions may be preferable
                return hash<int>()(key.id) ^ (hash<std::string>()(key.name) << 1);
            }
        };
    }
    
    int main() {
        std::unordered_map<MyKey, int> myUnorderedMap;
        MyKey key1{1, "apple"};
        MyKey key2{2, "banana"};
        myUnorderedMap[key1] = 10;
        myUnorderedMap[key2] = 20;
        return 0;
    }
    
  2. Pass the hasher as a template parameter:

    #include <unordered_map>
    #include <string>
    #include <functional>
    
    struct MyKey {
        int id;
        std::string name;
    
        // Define the "==" operator
        bool operator==(const MyKey& other) const {
            return id == other.id && name == other.name;
        }
    };
    
    // Define the hash structure
    struct MyKeyHash {
        size_t operator()(const MyKey& key) const {
            return std::hash<int>()(key.id) ^ (std::hash<std::string>()(key.name) << 1);
        }
    };
    
    int main() {
        // Pass MyKeyHash as the third template parameter
        std::unordered_map<MyKey, int, MyKeyHash> myUnorderedMap;
        MyKey key1{1, "apple"};
        MyKey key2{2, "banana"};
        myUnorderedMap[key1] = 10;
        myUnorderedMap[key2] = 20;
        return 0;
    }
    

In both cases, == operator is also required for std::unordered_map.

What needs to be done to use your class as a key in a… - sobes.tech