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

   2024-10-02 8920
核心提示:是的,C++的HashMap可以存储自定义类型。可以通过定义自定义类型的哈希函数和相等比较函数来实现,以确保HashMap可以正确地对自

是的,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正确地对自定义类型进行操作。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号