• 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 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 fileKey;
            std::map, 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.结果

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

  • 相关阅读:
    Spring源码相关
    如何将 Transformer 应用于时间序列模型
    vue3后台管理框架之技术栈
    OpenStack Icehouse 部署流程
    C++基础知识(十一)--- 文件读写
    计算机组成原理(一)计算机系统概论
    小程序如何使用订阅消息(PHP代码+小程序js代码)
    [附源码]java毕业设计在线二手车交易信息管理系统
    【计算机视觉】相机模型&立体视觉
    Android T 窗口层级其三 —— 层级结构树添加窗口(更新中)
  • 原文地址:https://blog.csdn.net/QIUCHUNHUIGE/article/details/127843414