14.1.3重学C++之【函数模板案例】

#include<iostream>
#include<stdlib.h>
#include<string>
using namespace std;


/*
    1.2.3函数模板案例
        利用函数模板封装一个排序的函数,可以对不同数据类型数组进行排序
        排序规则从大到小,排序算法为选择排序
*/


template<class T>
void my_swap(T&x, T&y){
    T temp = x;
    x = y;
    y = temp;
}


template<class T>
void my_sort(T & arr, int len){
    for(int i=0; i<len; i++){
        int temp_max = i;
        for(int j=i+1; j<len; j++){
            if(arr[temp_max] < arr[j]){
                temp_max = j;
            }
        }
        if(temp_max != i){
            my_swap(arr[temp_max], arr[i]);
        }
    }
}


template<class T>
void my_print(T & arr, int len){
    for(int i=0; i<len; i++){
        cout << arr[i] << " ";
    }
    cout << endl;
}


void test_1(){
    char char_arr[] = "cdgsauie";
    int num = sizeof(char_arr) / sizeof(char);
    my_sort(char_arr, num);
    my_print(char_arr, num);
}


void test_2(){
    int int_arr[] = {4,6,7,1,3,9,5};
    int num = sizeof(int_arr) / sizeof(int);
    my_sort(int_arr, num);
    my_print(int_arr, num);
}


int main(){
    test_1();
    test_2();

    system("pause");
    return 0;
}

posted @ 2021-04-17 20:05  yub4by  阅读(52)  评论(0)    收藏  举报