Sobes.tech
Middle+

Барои истифодаи синфи худ ҳамчун калид дар харита ё unordered_map чӣ бояд кард?

sobes.tech AI

Ҷавоб аз AI

Барои std::map:

Шумо бояд оператори муқоиса <-ро барои синфи худ муайян кунед.

#include <map>
#include <string>

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

    // Муайян кардани оператори "<"
    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:

Шумо бояд функсияи хеш (hash) барои синфи худ муайян кунед ва агар лозим бошад, оператори баробарии ==. Стандартии std::hash наметавонад типҳои истифодашударо хеш кунад.

Роҳҳои муайян кардани hash:

  1. Баровардани std::hash дар фазои номи std (тамоман тавсия намешавад):

    #include <unordered_map>
    #include <string>
    #include <functional> // Барои std::hash
    
    struct MyKey {
        int id;
        std::string name;
    
        // Муайян кардани оператори "=="
        bool operator==(const MyKey& other) const {
            return id == other.id && name == other.name;
        }
    };
    
    // Махсусгардонии std::hash барои MyKey
    namespace std {
        template <>
        struct hash<MyKey> {
            size_t operator()(const MyKey& key) const {
                // Мисоли соддаи омехта кардани hash-ҳо
                // Функсияҳои хеши мураккабтар ва устувортар метавонанд беҳтар бошанд
                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-ер ҳамчун параметри шаблонӣ:

    #include <unordered_map>
    #include <string>
    #include <functional>
    
    struct MyKey {
        int id;
        std::string name;
    
        // Муайян кардани оператори "=="
        bool operator==(const MyKey& other) const {
            return id == other.id && name == other.name;
        }
    };
    
    // Муайян кардани структураи 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() {
        // Дода кардани MyKeyHash ҳамчун параметри шаблонӣ
        std::unordered_map<MyKey, int, MyKeyHash> myUnorderedMap;
        MyKey key1{1, "apple"};
        MyKey key2{2, "banana"};
        myUnorderedMap[key1] = 10;
        myUnorderedMap[key2] = 20;
        return 0;
    }
    

Ҳарду ҳолат барои std::unordered_map инчунин оператори баробарии == талаб мекунанд.