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