使用 stl 中的 sort() 函数进行排序时,若数组中存在相同元素,则当 a==b 时必须返回 false,返回 true 则会报错如下:


原因在于 Visual Studio 中的 sort() 函数使用的是 strict weak orderings,详见 Strict weak orderings。
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool comp1(const int& a, const int& b) {
if (a > b) {
return true;
}
else if (a < b) {
return false;
}
// return true; // Error
return false;
}
bool comp2(const int& a, const int& b) {
// return a >= b; // Error
return a > b;
}
int main() {
vector<int> v1 = { 1, 5, 5, 2, 7 };
vector<int> v2(v1);
for (auto val : v1) {
cout << val << " ";
}
cout << endl;
// 1 5 5 2 7
sort(v1.begin(), v1.end(), comp1);
for (auto val : v1) {
cout << val << " ";
}
cout << endl;
// 7 5 5 2 1
for (auto val : v2) {
cout << val << " ";
}
cout << endl;
// 1 5 5 2 7
sort(v2.begin(), v2.end(), comp2);
for (auto val : v2) {
cout << val << " ";
}
cout << endl;
// 7 5 5 2 1
}