7

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での並べ替えのように機能しないのはなぜですか?

4

2 に答える 2

9

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::lessandを使用する場合は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

2 番目のソリューションの完全な例はこちらです。

于 2013-02-12T08:55:19.303 に答える
7

std::sortは、(通常)演算子に関して定義される厳密な弱い順序付けの考え方に基づいているため、そのように動作します。<

あなたの質問に関して; 現在、「とは異なる動作をするC関数を書きましたstd::sort。なぜ違うのですか?」のようです。答えは: 別の関数を書いたからです!

于 2013-02-12T08:43:11.817 に答える