四、函数模板示例:冒泡排序

  1. #include <iostream>
  2. #define N 10
  3. using namespace std;
  4. template<typename T>
  5. void mySwap(T& t1,T& t2){
  6. T temp = t1;
  7. t1 = t2;
  8. t2 = temp;
  9. }
  10. template<typename T> // 每个模板函数前面都要跟上一个模板声明,不然无法识别数据类型T
  11. void bubbleSort(T arr[],int len){
  12. for(int i = 1;i <= len-1;i++){
  13. for(int j = 0;j < len-i;j++){
  14. if(arr[j] > arr[j+1]){
  15. mySwap(arr[j],arr[j+1]);
  16. }
  17. }
  18. }
  19. }
  20. double a[N+1]; // 可以测试 int和double类型
  21. int main(){
  22. int n = 0;
  23. cin >> n;
  24. for(int i = 0;i < n;i++){
  25. cin >> a[i];
  26. }
  27. bubbleSort(a,n);
  28. for(int i = 0;i < n;i++){
  29. cout << a[i] << " ";
  30. }
  31. system("pause");
  32. return 0;
  33. }