|
來看看氣泡排序法: //
整數氣泡排序法
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> 執行結果:
在這個程式中,編譯器會自動產生兩個版本的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(),但您仍自行重載了一個函式以自行定義特定的函式功能。 |