• 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.结果

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

  • 相关阅读:
    五种多目标优化算法(MOGWO、MOJS、NSWOA、MOPSO、MOAHA)性能对比(提供MATLAB代码)
    Spring是如何整合JUnit的?JUnit源码关联延伸阅读
    C语言:指针的关系运算
    Mediacodec 如何硬件解码到纹理的
    【Spring Boot 集成应用】Actuator监控功能使用
    linux 系统内存诊断
    数据湖:OPPO数据湖统一存储技术实践
    Elasticsearch_第2章_ elasticsearch_进阶
    【Linux】多线程基础
    路径某个位置更换名称-python
  • 原文地址:https://blog.csdn.net/QIUCHUNHUIGE/article/details/127843414