C++ stable_sort 不稳定?

标签 c++ stl stable-sort

我正在使用 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/

相关文章:

c++ - 如何检测一个容器是否保证有序列存储

c++ - "stable_sort()ing"C++ 中的 STL <列表>

matlab - MATLAB 中的稳定 accumarray

iphone - C++ 代码的 XCode 编译错误

c++ - 在析构函数中访问静态成员的静态对象

c++ - 对已定义函数的 undefined reference

delphi - 向 TList 和 TStringList 添加稳定排序的简单方法

c++ - 如何正确报告 Linux 中另一个进程的突然结束?

c++ - 如何在 C++ 中使用 STL 将带空格的字符串连接成一个字符串

c++ - 是否有标准库函数可以反转 STL 堆栈?