c++

C++ HashMap可以存储自定义类型吗

小樊
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
看了该问题的人还看了