![](/img/trans.png)
[英]If std::greater<>, then why std::less (and not std::lesser<>)?
[英]confusion about using std::less and std::greater with std::sort
在 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, 10, 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,3,5,7,9,2,4,6,8,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, x+10, 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, x+10, g );
for( int i=0; i<10; i++ )
cout << x[i] << " ";
cout << endl;
// descending but ascending
sort( x, x+10, l );
for( int i=0; i<10; i++ )
cout << x[i] << " ";
cout << endl;
}
但我的期望並不正確。
為什么 STL 中的排序不像 C 中的排序那樣工作?
std::sort
默認按升序排序。 如果您正在尋找降序,這里有訣竅:
int x[10] = { 1,3,5,7,9,2,4,6,8,10 };
std::vector<int> vec(x, x+10); // construct std::vector object
std::sort(vec.rbegin(),vec.rend()); // sort it in reverse manner
這樣,您明確地說std::sort
應該將您的數組視為其結束是其開始,反之亦然,這會導致您的數組按降序排序。 這是完整的示例。
如果您想使用std::less
和std::greater
,則它可能如下所示:
int x[10] = { 1,3,5,7,9,2,4,6,8,10 };
std::sort(x, x + 10, std::less<int>()); // for ascending order
std::sort(x, x + 10, std::greater<int>()); // for descending order
第二種解決方案的完整示例在這里。
std::sort
行為如此,因為它基於嚴格弱排序的思想,它(通常)根據<
運算符定義。
至於你的問題; 目前似乎是“我編寫了一個與std::sort
行為不同的 C 函數。為什么不同?”。 答案是:因為你寫了一個不同的函數!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.