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

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

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

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

看下面一个例子:

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;
}

原文链接: https://www.cnblogs.com/xylc/p/5292371.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/230362

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月13日 下午2:39
下一篇 2023年2月13日 下午2:39

相关推荐