stable_sort的自定义比较功能

Ahm*_*d A 1 c++ stl

我想对一个数组进行排序int32_t,这样所有正数(包括零)首先出现,然后是所有负数.输出中+ ve和-ve数的相对顺序应与输入的顺序相同.例如

Input  : 9, 4, -2, -1, 5, 0, -5, -3, 2 <br>
Expected Output : 9, 4, 5, 0, 2, -2, -1, -5, -3
Run Code Online (Sandbox Code Playgroud)

但是,我得到以下输出:

Actual output : 2 0 5 4 9 -3 -5 -1 -2 <br>
Run Code Online (Sandbox Code Playgroud)

输出部分准确,+ ve然后-ve,但+ ve和-ve数列表相反.有人可以请帮助.

#include <iostream>
#include <algorithm>
using namespace std;


bool comp(int32_t lhs, int32_t rhs)
{
    if ( (lhs < 0) && (rhs >= 0) )
        return false;
    else
        return true;
}


int main()
{
    vector<int32_t> input{9, 4, -2, -1, 5, 0, -5, -3, 2};

    // sort +ve, then -ve
    stable_sort(input.begin(), input.end(), comp);
    for (int32_t i : input)
        cout << i << " ";
    cout << endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

艾哈迈德,谢谢你.

Ben*_*ley 5

您的比较函数不符合严格弱序的要求.具体而言,反思性.就是说,对所有人来说a,

comp(a,a)== false

例如,在函数中,comp(0,0)将返回true.试试这个:

bool comp(int32_t lhs, int32_t rhs)
{
    if (lhs < 0)
        return false;
    return rhs < 0;
}
Run Code Online (Sandbox Code Playgroud)

但实际上,您所描述的操作是一个分区.您最好使用std::stable_partition谓词来检查值是否> = 0.

auto ge_0 = [](int A) { return A >= 0; };
std::stable_parition(input.begin(), input.end(), ge_0);
Run Code Online (Sandbox Code Playgroud)