我正在使用 C++ stable_sort 使用比较器函数按升序对我的类对象的 vector 进行排序,但排序不稳定。一种可行的解决方法是反向迭代并反转比较器中的逻辑。但不明白为什么它不应该正常工作。 代码:
using namespace std;
class Pair{
string str;
int num;
public:
Pair(string s, int n):str(s), num(n)
{}
Pair(const Pair &a)
{
str = a.str;
num = a.num;
}
int Num()
{
return num;
}
string Str() const{
return str;
}
void set(string s, int n)
{
str = s;
num=n;
}
void print() const{
cout<<"\n"<<num<<" "<<str;
}
};
bool comparator( Pair a, Pair b)
{
return a.Num()<=b.Num();
}
int main() {
int n;
cin >> n;
vector<Pair> arr;
for(int a0 = 0; a0 < n; a0++){
int x;
string s;
cin >> x >> s;
if((a0+1)<=n/2)
s="-";
Pair p(s, x);
arr.push_back(p);
}
cout<<"\n Before sort";
for(auto i:arr)
i.print();
stable_sort(arr.begin(), arr.end(), comparator);
cout<<"\n\n After sort";
for(auto i:arr)
i.print();
return 0;
}
结果: 排序前 0 - 6 - 0 - 6 - 4 - 0 - 6 - 0 - 6 - 0 - 4那个 3是 0至 1是 5个问题 1 或 2 不 4是 2至 4个
排序后 0至 0 - 0 - 0 - 0 - 0 - 1 或 1是 2至 2 不 3是 4个 4是 4那个 4 - 5个问题 6 - 6 - 6 - 6 -
最佳答案
comp - comparison function object (i.e. an object that satisfies the requirements of Compare) which returns true if the first argument is less than (i.e. is ordered before) the second.
来自 stable_sort .比较器必须实现严格的弱排序。另见 here获取确切要求的表格。
你的比较器是错误的,它也为相等的元素返回 true。
关于C++ stable_sort 不稳定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50085982/