數列

(1 , 3)

(2 , 6)

(3 , 4)

(4 , 7)

(5 , 8)

(6 , 9)

(7 , 1)

(8 , 0)

若用後面數字做比較,小到大排序

則排序後應該是

(8 , 0)

(7 , 1)

(1 , 3)

(3 , 4)

(2 , 6)

(4 , 7)

(5 , 8)

(6 , 9)

 

問題是該怎麼做呢?

這裡我們用內建函數 qsort  做說明

 

qsort(base, length, sizeof(element), compare);

 

base 為陣列的起始位址

length 代表有幾個元素

sizeof(element) 一個元素的大小  

compare 自訂的比較方法

 

因為 qsort 以 void * 接納各種型態  

所以 qsort 無法得知一個元素的大小,也就是位移量 

因此,我們必須在第三個參數告訴它

 

#include <algorithm>
#include <iostream>

using namespace std;

int cmp1(const void *_a, const void *_b)
{
    const int *a = (const int *)_a,
              *b = (const int *)_b;

    return a[1] > b[1];
}

int cmp2(const void *_a, const void *_b)
{
    const int *a = *(const int * const *)_a,
              *b = *(const int * const *)_b;

    return a[1] > b[1];
}


int main()
{
    constexpr int len = 2;
    int arr1[10][len];

    for(int i = 0; i<10; i+=1)
        for(int j = 0; j<len; j+=1)
            arr1[i][j] = len-j;
    
    qsort(arr1, 10, sizeof(arr1[0]), cmp1);


    int **arr2 = new int*[10];
    for(int i = 0; i<10; i+=1){
        arr2[i] = new int[len];
        for(int j = 0; j<len; j+=1)
            arr2[i][j] = rand()%10;
    }


    cout << "before:" << endl;
    for(int i = 0; i<10; i+=1)
        cout << "(" << arr2[i][0] << ", " << arr2[i][1] << ")" << endl;
    cout << endl;

    qsort(arr2, 10, sizeof(arr2[0]), cmp2);

    cout << "\nafter:" << endl;
    for(int i = 0; i<10; i+=1)
        cout << "(" << arr2[i][0] << ", " << arr2[i][1] << ")" << endl;
    cout << endl;

}

arrow
arrow
    全站熱搜

    大神(偽) 發表在 痞客邦 留言(0) 人氣()