zoukankan      html  css  js  c++  java
  • c++ std::sort函数调用经常出现的invalidate operator<错误原因以及解决方法

    在c++编程中使用sort函数,自定义一个数据结构并进行排序时新手经常会碰到这种错误。

    这是为什么呢?原因在于什么?如何解决?

    看下面一个例子:

    int main(int, char*[])
    {
        struct ItemDesc
        {
            int val;
            std::string content;
        };
        std::vector<ItemDesc> dataList = {
            ItemDesc{ 0, "hello" },
            ItemDesc{ 1, "aello" },
            ItemDesc{ 2, "hello" },
            ItemDesc{ 3, "xello" },
            ItemDesc{ 0, "hellx" }
        };
        std::sort(dataList.begin(), dataList.end(), [](const ItemDesc& lhs, const ItemDesc& rhs){
            return (lhs.val <= rhs.val);
        });
        return 0;
    }

    这段代码在vs2013上就会触发上述断言错误。

    std::sort可能在比较的过程中对同一对数据进行多次比较,必须保证同一对数据多次比较结果是一致的。即:

    当lhs为ItemDesc{ 0, "hello" },而rhs为ItemDesc{ 0, "hellx" },返回true,第二次比较并且顺序交换后,即ItemDesc{ 0, "hellx" },而rhs为ItemDesc{ 0, "hello" },它应该返回false。

    而上述函数无法保证这一点。

    所以可以改成下面这样:

    int main(int, char*[])
    {
        struct ItemDesc
        {
            int val;
            std::string content;
        };
        std::vector<ItemDesc> dataList = {
            ItemDesc{ 0, "hello" },
            ItemDesc{ 1, "aello" },
            ItemDesc{ 2, "hello" },
            ItemDesc{ 3, "xello" },
            ItemDesc{ 0, "hellx" }
        };
        std::sort(dataList.begin(), dataList.end(), [](const ItemDesc& lhs, const ItemDesc& rhs){
            //main filed
            if (lhs.val < rhs.val)
            {
                return true;
            }else if (lhs.val > rhs.val)
            {
                return false;
            }
            else
            {
                //compare other data filed
                //...
                return lhs.content < rhs.content;
            }
        });
        return 0;
    }
  • 相关阅读:
    接口测试断言详解(Jmeter)
    接口测试参数化详解(Jmeter)
    记一次线上内存泄漏问题的排查过程
    BI入门经典(转载)
    图形初阶
    数据的输入
    来自 Google 的 R 语言编码风格指南
    提醒程序员注意的一些事项--R
    R语言-attach、detach、with
    R数据类型
  • 原文地址:https://www.cnblogs.com/xylc/p/5292371.html
Copyright © 2011-2022 走看看