Sobes.tech
Middle+

¿Qué se necesita hacer para usar tu clase como clave en un mapa o unordered_map?

sobes.tech AI

Respuesta de la IA

Para std::map:

Es necesario definir el operador de comparación < para tu clase.

#include <map>
#include <string>

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

    // Definir el operador "<"
    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;
}

Para std::unordered_map:

Es necesario definir una función de hash (hasher) para tu clase y, si es necesario, el operador de comparación de igualdad ==. El hash estándar std::hash no puede hacer hash de tipos personalizados.

Formas de definir el hash:

  1. Sobrecargar std::hash en el espacio de nombres std (no recomendado):

    #include <unordered_map>
    #include <string>
    #include <functional> // Para std::hash
    
    struct MyKey {
        int id;
        std::string name;
    
        // Definir el operador "=="
        bool operator==(const MyKey& other) const {
            return id == other.id && name == other.name;
        }
    };
    
    // Especialización de std::hash para MyKey
    namespace std {
        template <>
        struct hash<MyKey> {
            size_t operator()(const MyKey& key) const {
                // Ejemplo de combinación simple de hashes
                // Funciones hash más complejas y robustas pueden ser preferibles
                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. Pasar el hash como parámetro de plantilla:

    #include <unordered_map>
    #include <string>
    #include <functional>
    
    struct MyKey {
        int id;
        std::string name;
    
        // Definir el operador "=="
        bool operator==(const MyKey& other) const {
            return id == other.id && name == other.name;
        }
    };
    
    // Definición de la estructura del hash
    struct MyKeyHash {
        size_t operator()(const MyKey& key) const {
            return std::hash<int>()(key.id) ^ (std::hash<std::string>()(key.name) << 1);
        }
    };
    
    int main() {
        // Pasar MyKeyHash como tercer parámetro de plantilla
        std::unordered_map<MyKey, int, MyKeyHash> myUnorderedMap;
        MyKey key1{1, "apple"};
        MyKey key2{2, "banana"};
        myUnorderedMap[key1] = 10;
        myUnorderedMap[key2] = 20;
        return 0;
    }
    

En ambos casos, también se requiere el operador de comparación de igualdad == para std::unordered_map.