在C中,sort通常实现,如下例所示:
- #include <stdio.h>
- void Sort( int* arr,int n,bool(*cmp)(int,int) )
- {
- for( int i=0; i<n-1; i++ )
- {
- for( int j=i+1; j<n; j++ )
- {
- if( cmp(arr[i],arr[j]) )
- swap( arr[i],arr[j] );
- }
- }
- }
- int ascending( int a,int b ) { return a > b; } // greater
- int descending( int a,int b ) { return a < b; } // less
- void main()
- {
- int arr[10] = { 1,3,5,7,9,2,4,6,8,10 };
- // ascending
- Sort( arr,10,ascending );
- for( int i=0; i<10; i++ )
- printf( "%d ",arr[i] );
- printf( "\n" );
- // descending
- Sort( arr,descending );
- for( int i=0; i<10; i++ )
- printf( "%d ",arr[i] );
- printf( "\n" );
- }
所以我在下面的例子中编写了一些源代码,期望得到相同的结果:
- #include <iostream>
- #include <algorithm> // for sort
- #include <functional> // for less & greater
- using namespace std;
- bool gt( int a,int b ) { return a > b; } // greater
- bool ls( int a,int b ) { return a < b; } // less
- void main()
- {
- int x[10] = { 1,10 };
- // ascending but descending
- sort( x,x+10,gt );
- for( int i=0; i<10; i++ )
- cout << x[i] << " ";
- cout << endl;
- // descending but ascending
- sort( x,ls );
- for( int i=0; i<10; i++ )
- cout << x[i] << " ";
- cout << endl;
- greater<int> g; // a > b
- less<int> l; // a < b
- // ascending but descending
- sort( x,g );
- for( int i=0; i<10; i++ )
- cout << x[i] << " ";
- cout << endl;
- // descending but ascending
- sort( x,l );
- for( int i=0; i<10; i++ )
- cout << x[i] << " ";
- cout << endl;
- }
但我的期望并不正确.
为什么在STL中排序不像C中的排序?
解决方法
std :: sort的行为与此类似,因为它基于
strict weak ordering的概念,它通常根据<操作符. 至于你的问题;它目前似乎是“我写了一个与std :: sort行为不同的C函数.为什么它不同?”.答案是:因为你写了不同的功能!