Sobes.tech
Middle+

Синфиңерди map же 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 үчүн:

Класска хеш функциясын (hasher) жана керек болсо, == барабарлык операторун аныктоо керек. Стандарттык std::hash колдонуучу типтерди хештөө мүмкүнчүлүгүнө ээ эмес:

Хешти аныктоо жолдору:

  1. std::hash-ти std кеңейтүүсүндө кайра жүктөө (кеңеш берилбейт):

    #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;
        }
    };
    
    // MyKey үчүн `std::hash` кеңейтүүсү
    namespace std {
        template <>
        struct hash<MyKey> {
            size_t operator()(const MyKey& key) const {
                // Жөнөкөй хештердин аралашмасы
                // Көбүрөөк татаал жана туруктуу хеш функциялар артыкчылыкка ээ болушу мүмкүн
                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. Хешерди шаблондук параметр катары берүү:

    #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;
        }
    };
    
    // Хешер структурасын аныктоо
    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 үчүн == барабарлык оператору да керек болот.