std::sort crash問題原因及解決方案

C++程序開發(fā)中我們常用std::sort函數(shù)對(duì)一個(gè)vector數(shù)組進(jìn)行排序,但是某些情況下會(huì)產(chǎn)生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});
    
    // 錯(cuò)誤的寫法
    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函數(shù)要滿足strict weak ordering的要求,即當(dāng)在比較函數(shù)中比較兩個(gè)對(duì)象時(shí),如果比較條件完全一樣,此時(shí)一定要返回false。
關(guān)于strict weak ordering的解釋,見:https://stackoverflow.com/questions/979759/operator-and-strict-weak-ordering/981299#981299

所以上述代碼要修改比較函數(shù)的實(shí)現(xiàn)即可:

#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;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容