四、函数模板示例:冒泡排序
#include <iostream>
#define N 10
using namespace std;
template<typename T>
void mySwap(T& t1,T& t2){
T temp = t1;
t1 = t2;
t2 = temp;
}
template<typename T> // 每个模板函数前面都要跟上一个模板声明,不然无法识别数据类型T
void bubbleSort(T arr[],int len){
for(int i = 1;i <= len-1;i++){
for(int j = 0;j < len-i;j++){
if(arr[j] > arr[j+1]){
mySwap(arr[j],arr[j+1]);
}
}
}
}
double a[N+1]; // 可以测试 int和double类型
int main(){
int n = 0;
cin >> n;
for(int i = 0;i < n;i++){
cin >> a[i];
}
bubbleSort(a,n);
for(int i = 0;i < n;i++){
cout << a[i] << " ";
}
system("pause");
return 0;
}