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;
    }
  • 相关阅读:
    linux操作系统及内核
    2.1.1Remove Duplicates from Sorted Arr
    顺序表
    开博篇
    ssh无法root用户登录与登录界面无法选择用户登录
    Ubuntu 18.04 Server安装GUI桌面
    Linux 命令 su 和 sudo 区别
    坑(二十六)—— mysql出现ERROR1698(28000):Access denied for user root@localhost错误解决方法
    redhat安装wps
    gitlab重置root密码
  • 原文地址:https://www.cnblogs.com/xylc/p/5292371.html
Copyright © 2011-2022 走看看