std::map中的自定义key避免踩坑

一、自定义key的结构体

typedef struct ST_PlanFileKey
{
    int ctIndex = -1;
    int planIndex = -1;
    bool operator <(const ST_PlanFileKey& data) const
    {
        return planIndex < data.planIndex;
    }
} PlanFileKey;

二、测试代码

        PlanFileKey fileKey;
        std::map<PlanFileKey, int> testMap;
        fileKey.ctIndex = 0;
        fileKey.planIndex = 0;
        testMap[fileKey] = 1;
        fileKey.planIndex = 2;
        testMap[fileKey] = 2;
        fileKey.planIndex = 3;
        testMap[fileKey] = 3;
        //
        fileKey.ctIndex = 1;
        fileKey.planIndex = 2;

        if (testMap.end() != testMap.find(fileKey))
        {
            qDebug() << "" << testMap[fileKey];        //qt的输出,类似于std::out
        }

1.结果

大家可以猜测下,是否会有输出?

实际这个会输出2,那也就是说,fileKey(ctIndex=1,planIndex=2)的key匹配到了fileKey(ctIndex=0,planIndex=2)的值,神不神奇?

答案:调用find的时候,会去执行operator <函数,对于自定义key有多个值的时候,必须每个值都进行判断,有个优先级。如下修改即可

 bool operator <(const ST_PlanFileKey& data) const
    {
        if (ctIndex != data.ctIndex)
        {
            return  ctIndex < data.ctIndex;
        }

        return planIndex < data.planIndex;
    }

三、测试代码2

std::pair<int, int> fileKey;
        std::map<std::pair<int, int>, int> testMap;
        fileKey.first = 0;
        fileKey.second = 0;
        testMap[fileKey] = 1;
        fileKey.second = 2;
        testMap[fileKey] = 2;
        fileKey.first = 1;

        if (testMap.end() != testMap.find(fileKey))
        {
            qDebug() << "" << testMap[fileKey];
        }

1.结果

这边并不输出任何值,说明没有匹配上。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值