c++ - C++ stable_sort 不稳定?
问题描述
我正在使用 C++ stable_sort 使用比较器函数按升序对类对象的向量进行排序,但排序不稳定。一个可行的解决方法是反向迭代并反转比较器中的逻辑。但无法理解为什么它不应该正常工作。代码:
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.
from stable_sort. The comparator must implement a strict weak ordering. See also here for a table of the exact requirements.
Your comparator is wrong, it also returns true for equal elements.
推荐阅读
- matlab - V-cycle Multigrid Poisson Matlab实现的伪代码
- javascript - 无法在 elenctron 上执行 cause=exit status 1 errorOut
- asp.net-mvc - 如何将日期时间从 API 传递到 postgresql db,后者接收没有区域时间的时间戳?
- python-2.7 - 无法为 PyPy2.7 安装 opencv-python
- operating-system - 文件格式是否独立于系统的字节序?
- python - 你没有权限使用这个命令 Discord.py 重写
- assembly - 为什么当我使用立即值打印整数时它工作正常,但如果我尝试打印包含整数的标签它不打印任何东西?
- fortran - 执行带有阶跃校正的 Runge-Kutta 方法时的无限循环
- python - 如何解决特定字段.E304错误
- grep - Grep 查找以 " 后跟 10 位数字 ","" 开头的行