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;
}
网友评论