溫馨提示×

C++ HashMap可以存儲自定義類型嗎

c++
小樊
84
2024-08-02 18:26:13
欄目: 云計算

是的,C++的HashMap可以存儲自定義類型??梢酝ㄟ^定義自定義類型的哈希函數和相等比較函數來實現,以確保HashMap可以正確地對自定義類型進行存儲和查找操作。以下是一個簡單的示例:

#include <iostream>
#include <unordered_map>

// 定義自定義類型
struct CustomType {
    int id;
    std::string name;

    bool operator==(const CustomType& other) const {
        return id == other.id && name == other.name;
    }
};

// 定義自定義類型的哈希函數
struct CustomTypeHash {
    std::size_t operator()(const CustomType& custom) const {
        return std::hash<int>()(custom.id) ^ (std::hash<std::string>()(custom.name) << 1);
    }
};

int main() {
    std::unordered_map<CustomType, int, CustomTypeHash> customMap;

    CustomType c1 = {1, "Alice"};
    CustomType c2 = {2, "Bob"};

    customMap[c1] = 10;
    customMap[c2] = 20;

    std::cout << "c1 value: " << customMap[c1] << std::endl;
    std::cout << "c2 value: " << customMap[c2] << std::endl;

    return 0;
}

在上面的示例中,我們定義了一個自定義類型CustomType,并定義了CustomTypeHash結構體來作為它的哈希函數。然后我們使用std::unordered_map來存儲CustomType類型的鍵值對。通過定義CustomType的相等比較函數和哈希函數,我們可以確保HashMap正確地對自定義類型進行操作。

0