2013-02-12 52 views
6

在C,排序通常執行如下面的例子:混淆使用std ::少和std ::有更大的std ::排序

#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; 
} 

但我的期望是不正確的。

爲什麼不按照C排序在STL工作?

回答

6

std::sort表現得如此,因爲它基於strict weak ordering的想法,該想法是(通常)根據<運算符定義的。

至於你的問題;它目前似乎是「我寫了一個C函數,其行爲與std::sort不同,它爲什麼不同?」。答案是:因爲你寫了一個不同的功能!

+0

我從你那裏得到了一個主意!謝謝,夥計! – user2063889 2013-02-13 02:11:39

8

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應該把你的數組作爲它的終點是它的開始,反之亦然,這將導致數組中進行排序在降序。 Here's the full example.


而如果你想使用std::lessstd::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 

用第二溶液全部例子是here