std::sort crash问题原因及解决方案

C++程序开发中我们常用std::sort函数对一个vector数组进行排序,但是某些情况下会产生crash的情况,比如下面的代码:

#include <iostream>
#include <algorithm>
#include <vector>

struct Node {
    int id;
    int value;
};

int main()
{
    std::vector<Node> allNodes;

    allNodes.push_back({0, 100});
    allNodes.push_back({1, 200});
    allNodes.push_back({2, 100});
    
    // 错误的写法
    std::sort(allNodes.begin(), allNodes.end(), [] (Node& a, Node& b)->bool {
        return (a.value <= b.value);
    });

    for (auto& it : allNodes) {
        std::cout << "id = " << it.id << ", value = " << it.value << std::endl;
    }

    return 0;
}

究其原因是sort函数要满足strict weak ordering的要求,即当在比较函数中比较两个对象时,如果比较条件完全一样,此时一定要返回false。
关于strict weak ordering的解释,见:https://stackoverflow.com/questions/979759/operator-and-strict-weak-ordering/981299#981299

所以上述代码要修改比较函数的实现即可:

#include <iostream>
#include <algorithm>
#include <vector>

struct Node {
    int id;
    int value;
};

int main()
{
    std::vector<Node> allNodes;

    allNodes.push_back({0, 100});
    allNodes.push_back({1, 200});
    allNodes.push_back({2, 100});

    // 正确的写法
    std::sort(allNodes.begin(), allNodes.end(), [] (Node& a, Node& b)->bool {
        if (a.value != b.value) {
            return (a.value < b.value);
        }
        return false;
    });

    for (auto& it : allNodes) {
        std::cout << "id = " << it.id << ", value = " << it.value << std::endl;
    }

    return 0;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容