unordered_map map 自定义key

本文介绍了如何使用自定义结构作为 C++ STL 中 map 和 unordered_map 的键。对于 map, 需要定义 operator< 以进行排序;对于 unordered_map, 则需要特例化 std::hash 以实现哈希计算。
#include <map>
#include <unordered_map>

class mapStruct
{
    int x;

public:
    bool operator<(mapStruct b) const { return this->x < b.x; }
    // bool operator==(const myStruct b) { return this->x == b.x; }
};

class unordermapStruct
{
    int x;

public:
    bool operator<(unordermapStruct b) const { return this->x < b.x; }
    // bool operator==(unordermapStruct b) const { return this->x == b.x; }
};

template <>
class std::hash<unordermapStruct>
{
    std::size_t operator()(const unordermapStruct &a) const
    {
        return 1;
    }
};

int main()
{
    mapStruct a;

    unordermapStruct b;
    std::map<mapStruct, int> myMap;

    std::unordered_map<unordermapStruct, int> myUnorderMap;
    myMap[a] = 1;
    return 0;
}

/**
1. map中key如果是自定义结构, 需要定义operator < 用于排序比较
2. unordered_map 中的key如果是自定义结构, 需要特例化std::hash<CustomerStruct>
 * **/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值