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;
}
复制代码
posted @   *神气*  阅读(1636)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 单线程的Redis速度为什么快?
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示