模版函数

来源:互联网 发布:遗传算法c程序 编辑:程序博客网 时间:2024/05/01 13:20
#include <iostream>using namespace std;template <typename T>void MySwap(T& a,T& b){    T t = a;    a = b;    b = t;}void run(){    cout << "int 交换(自动类型推导)" << endl;    int a = 1;    int b = 2;    cout << "a = " << a << ",b = " << b << endl;    MySwap(a,b);    cout << "a = " << a << ",b = " << b << endl;    cout << "float 交换(显式类型推导)" << endl;    float fa = 3.5;    float fb = 4.9;    cout << "fa = " << fa << ",fb= " << fb << endl;    MySwap<float>(fa,fb);    cout << "fa = " << fa << ",fb= " << fb << endl;}template<typename T>void SelectSort(T array[],int length){    for(int i=0;i<length;i++)    {        int k = i;        for(int j=i+1;j<length;j++)        {            if(array[k] < array[j])            {                k = j;            }        }        if(k!=i)        {            MySwap(array[i],array[k]);  //自动类型推导        }    }}void test_1(){    int array[] = {5,2,3,1,4};    int length = sizeof(array)/sizeof(array[0]);    cout << "All elements: " << endl;    for(int i=0;i<length;i++)    {        cout << array[i] << endl;    }    SelectSort<int>(array,length);  //显示类型推导    cout << "After sorting..." << endl;    for(int i=0;i<length;i++)    {        cout << array[i] << endl;    }}void test_2(){    char array[] = {'d','a','c','b','m'};    int length = sizeof(array)/sizeof(array[0]);    cout << "All Elements : " << endl;    for(int i=0;i<length;i++)    {        cout << array[i] << endl;    }    SelectSort<char>(array,length);  //显示类型推导    cout << "After sorting..." << endl;    for(int i=0;i<length;i++)    {        cout << array[i] << endl;    }}int main(){//    run();//    test_1();    test_2();    cout << "------end-----" << endl;    return 0;}
0 0
原创粉丝点击