發新話題

C++ Gossip《範本、名稱空間》 函式範本

C++ Gossip《範本、名稱空間》 函式範本

來看看氣泡排序法:
// 整數氣泡排序法

void bubbleSort(int number[], int length) {
    int i, j, k, flag = 1;
    int tmp;

    for(i = 0; i < length-1 && flag == 1; i++) {
        flag = 0;
        for(j = 0; j < length-i-1; j++) {
            if(number[j+1] < number[j]) {
                tmp = number[j];
                number[j] = number[j+1];
                number[j+1] = tmp;
                flag = 1;
            }
        }
    }
}

// 浮點數氣泡排序
void bubbleSort(float number[], int length) {
    int i, j, k, flag = 1;
    float tmp;

    for(i = 0; i < length-1 && flag == 1; i++) {
        flag = 0;
        for(j = 0; j < length-i-1; j++) {
            if(number[j+1] < number[j]) {
                tmp = number[j];
                number[j] = number[j+1];
                number[j+1] = tmp;
                flag = 1;
            }
        }
    }
}


函式範本(Function template)又稱「通用函式」(Generic function),它可以適用於不同資料型態的參數列,但實作內容相同的函式,以上面的氣泡排序法為例,除了參數列資料型態不同之外,其實排序的程式碼幾乎相同,實在沒必要為了資料型態的不同而重覆撰寫相同的程式碼。

建立函式範本的方法之一是使用"template"關鍵字,並使用class來宣告取代用的資料型態宣告字,使用下面這個程式作個示範:

#include <iostream>
using namespace std;

template <class X>
void bubbleSort(X[], int);

int main() {
    int iarr[] = {5, 3, 11, 6, 8, 9, 20, 11};
    float farr[] =  {5.1, 3.4, 11.3, 6.6, 8.9, 9.11, 20.2, 11.4};

    bubbleSort(iarr, 8);
    for(int i = 0; i < 8; i++)
        cout << " " << iarr;
    cout << endl;

    bubbleSort(farr, 8);
    for(int i = 0; i < 8; i++)
        cout << " " << farr;
    cout << endl;
   
    return 0;
}

template <class X>
void bubbleSort(X number[], int length) {
    int i, j, k, flag = 1;
    X tmp;

    for(i = 0; i < length-1 && flag == 1; i++) {
        flag = 0;
        for(j = 0; j < length-i-1; j++) {
            if(number[j+1] < number[j]) {
                tmp = number[j];
                number[j] = number[j+1];
                number[j+1] = tmp;
                flag = 1;
            }
        }
    }
}
執行結果:
  3 5 6 8 9 11 11 20
3.4 5.1 6.6 8.9 9.11 11.3 11.4 20.2

在這個程式中,編譯器會自動產生兩個版本的bubbleSort()函式,一個是整數陣列的參數,一個是浮點數陣列的參數,也可以使用"typename"來取代class關鍵字,例如:
template <typename X>
void bubbleSort(X number[], int length) {
    ....
}


"typename"是後來才加入至C++中的,早期的撰寫風格主要都是使用"class"。

在宣告了函式範本之後,您還是可以自行重載函式,例如:
template <class X>
void bubbleSort(X number[], int length) {
....
}

void bubbleSort(int number[], int length, int descend) {
// 以descend決定要由大至小或由小至大排序
....
}


在這個程式片段中,雖然您宣告了樣版函式bubbSort(),但您仍自行重載了一個函式以自行定義特定的函式功能。

TOP

發新話題

本站所有圖文均屬網友發表,僅代表作者的觀點與本站無關,如有侵權請通知版主會盡快刪除。