使用类似的比较功能时,C ++中的std:sort获得不同的结果

时间:2018-08-09 07:14:13

标签: c++ sorting std

我正在尝试使用arr [i]-X的绝对值对数组进行排序。X是程序中提供的值。对于传递给std :: sort的两个比较,我得到了不同的结果。有人可以解释为什么这两个比较产生不同的结果。

#include<bits/stdc++.h>
using namespace std;

struct  {
int x;
bool operator()(int a, int b) const
    {   
        return abs(a-x) < (b-x);
    }   

}customCompare;

void rearrange2(int arr[], int n , int x) {
customCompare.x = x;
std::sort(arr, arr+n, customCompare);    

}

void rearrange1(int arr[], int n , int x) {

std::sort(arr, arr+n, [x](int a , int b) {return abs(a-x) < abs(b-x);});
}
void printArray(int arr[] , int n)
{
for (int i = 0 ; i < n; i++)
    cout << arr[i] << " ";
}

int main()
{

int n = sizeof(arr)/sizeof(arr[0]);
int x = 7;
int arr1[] = {10, 5, 3, 9 ,2};
cout << "\n rearrange 1\n";
rearrange1(arr1,n,x);
printArray(arr1,n);

int arr2[] = {10, 5, 3, 9 ,2};
cout << "\n rearrage 2 \n";
rearrange2(arr2,n,x);
printArray(arr2,n);
return 0;
} 

我得到的输出是

重新排列1 5 9 10 3 2  重装2 5 10 3 9 2

1 个答案:

答案 0 :(得分:1)

这可能是因为abs(a-x) < (b-x)不等于abs(a-x) < abs(b-x)。 我想这只是您的错字。