C++ 为std得到不同的结果:在c+中排序+;使用相似比较函数时

C++ 为std得到不同的结果:在c+中排序+;使用相似比较函数时,c++,sorting,std,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); }

我试图使用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;
} 
#包括
使用名称空间std;
结构{
int x;
布尔运算符()(整数a,整数b)常量
{   
返回abs(a-x)<(b-x);
}   
}习惯比较;
无效重新排列2(整数arr[],整数n,整数x){
customCompare.x=x;
标准::排序(arr、arr+n、customCompare);
}
无效重新排列1(整数arr[],整数n,整数x){
排序(arr,arr+n,[x](inta,intb){返回abs(a-x)cout这可能是因为
abs(a-x)<(b-x)
并不等同于
abs(a-x)

我猜这只是你的一个输入错误。

一个在两边都使用了
abs
,另一个没有。
int n=sizeof(arr)/sizeof(arr[0])
什么是arr,你从哪里得到的?从它看起来,n比5大,这是arr1和arr2的大小。