关闭

模版函数

89人阅读 评论(0) 收藏 举报
分类:
#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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:109671次
    • 积分:2896
    • 等级:
    • 排名:第12789名
    • 原创:175篇
    • 转载:67篇
    • 译文:0篇
    • 评论:10条
    最新评论