Sobes.tech
Middle+

Co należy zrobić, aby użyć swojej klasy jako klucza w mapie lub unordered_map?

sobes.tech AI

Odpowiedź od AI

Dla std::map:

Należy zdefiniować operator porównania < dla Twojej klasy.

#include <map>
#include <string>

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

    // Definiujemy 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;
}

Dla std::unordered_map:

Należy zdefiniować funkcję haszującą (hasher) dla Twojej klasy oraz, jeśli to konieczne, operator porównania ==. Standardowy hasz std::hash nie obsługuje typów użytkownika.

Sposoby definiowania haszera:

  1. Przeciążenie std::hash w przestrzeni nazw std (niezalecane):

    #include <unordered_map>
    #include <string>
    #include <functional> // Dla std::hash
    
    struct MyKey {
        int id;
        std::string name;
    
        // Definiujemy operator "=="
        bool operator==(const MyKey& other) const {
            return id == other.id && name == other.name;
        }
    };
    
    // Specjalizacja std::hash dla MyKey
    namespace std {
        template <>
        struct hash<MyKey> {
            size_t operator()(const MyKey& key) const {
                // Przykład prostego łączenia hashy
                // Bardziej skomplikowane i odporne funkcje hash mogą być preferowane
                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. Przekazywanie haszera jako parametru szablonu:

    #include <unordered_map>
    #include <string>
    #include <functional>
    
    struct MyKey {
        int id;
        std::string name;
    
        // Definiujemy operator "=="
        bool operator==(const MyKey& other) const {
            return id == other.id && name == other.name;
        }
    };
    
    // Definicja struktury haszera
    struct MyKeyHash {
        size_t operator()(const MyKey& key) const {
            return std::hash<int>()(key.id) ^ (std::hash<std::string>()(key.name) << 1);
        }
    };
    
    int main() {
        // Przekazujemy MyKeyHash jako trzeci parametr szablonu
        std::unordered_map<MyKey, int, MyKeyHash> myUnorderedMap;
        MyKey key1{1, "apple"};
        MyKey key2{2, "banana"};
        myUnorderedMap[key1] = 10;
        myUnorderedMap[key2] = 20;
        return 0;
    }
    

W obu przypadkach, dla std::unordered_map, konieczne jest również zdefiniowanie operatora ==.