通过对一个排序算法的编写,加深理解函数模板即为:类型的参数化
#include<iostream> using namespace std; //让字符数据和 int型数据进行排序 template<typename T1,typename T2> int mySort(T1* array, T2 size) { T2 temp = 0; if (array == NULL) { return -1; } for (int i = 0; i < size; i++) { for (int j = i + 1; j < size; j++) { if (array[i] < array[j]) { temp = array[i]; array[i] = array[j]; array[j] = temp; } } } return 0; } template<typename T1,typename T2> int myPrint(T1* array, T2 size) { for (int i = 0; i < size; i++) { cout << array[i]; } cout << endl; return 0; } int main() { //int 类型语句块 { int myArray[] = { 11,22,13,54,44,2,5,6 }; int size = sizeof(myArray) / sizeof(*myArray); mySort<int, int>(myArray, size); cout << "排序之后" << endl; myPrint(myArray, size); } //chra类型语句块 { char buf[] = "Afasdwafasdfad"; int len = strlen(buf); mySort<char, int>(buf, len); cout << "排序之后" << endl; myPrint(buf, len); } system("pause"); return 0; }
输出结果: