Sobes.tech
Middle+

Mida tuleb teha, et oma klassi kasutada võtmena map või unordered_map'is?

sobes.tech AI

Vastus AI-lt

Std::map jaoks:

Teil tuleb määratleda võrdlusoperaator < teie klassile.

#include <map>
#include <string>

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

    // Määratleme `<` operaatori
    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;
}

Std::unordered_map jaoks:

Teil tuleb määratleda hash-funktsioon (hasher) teie klassile ning vajadusel võrdlusoperaator ==. Standardne std::hash ei toeta kasutaja määratletud tüüpe:

Hash-funktsiooni määratlemise viisid:

  1. Üle kirjutada std::hash std nimelahtris (mitte soovitatav):

    #include <unordered_map>
    #include <string>
    #include <functional>
    
    struct MyKey {
        int id;
        std::string name;
    
        // Määratleme `==` operaatori
        bool operator==(const MyKey& other) const {
            return id == other.id && name == other.name;
        }
    };
    
    // Spetsialiseerime `std::hash` MyKey jaoks
    namespace std {
        template <>
        struct hash<MyKey> {
            size_t operator()(const MyKey& key) const {
                // Lihtne hash-kombinatsioon
                // keerukamad ja stabiilsemad hash-funktsioonid võivad olla eelistatud
                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. Hash-funktsiooni edastamine malliparameetrina:

    #include <unordered_map>
    #include <string>
    #include <functional>
    
    struct MyKey {
        int id;
        std::string name;
    
        // Määratleme `==` operaatori
        bool operator==(const MyKey& other) const {
            return id == other.id && name == other.name;
        }
    };
    
    // Hash-struktuuri määratlus
    struct MyKeyHash {
        size_t operator()(const MyKey& key) const {
            return std::hash<int>()(key.id) ^ (std::hash<std::string>()(key.name) << 1);
        }
    };
    
    int main() {
        // Edastame `MyKeyHash` kolmandana malliparameetrina
        std::unordered_map<MyKey, int, MyKeyHash> myUnorderedMap;
        MyKey key1{1, "apple"};
        MyKey key2{2, "banana"};
        myUnorderedMap[key1] = 10;
        myUnorderedMap[key2] = 20;
        return 0;
    }
    

Mõlemas juhul on std::unordered_map-i jaoks vajalik ka võrdlusoperaator ==.