设为首页 加入收藏

TOP

练习c++ 函数模版例子
2012-11-13 13:25:25 】 浏览:558
Tags:练习   函数 模版 例子
    [cpp]
   
    //函数模版使用
   
    //函数模版标准不支持参数默认值
   
    #include<iostream>
   
    #include<cstring>
   
    using namespace std;
   
    template <typename T>
   
    void sort(T* a,int n)//普通冒泡排序
   
    {
   
    bool changed;
   
    do
   
    {
   
    changed=false;
   
    for(int i=1;i<n;i++)
   
    {
   
    if(a[i]<a[i-1])
   
    {
   
    swap(a[i],a[i-1]);
   
    changed=true;
   
    }
   
    }
   
    --n;
   
    }
   
    while(changed);
   
    }
   
    template <>//模版特化
   
    void sort(const char* a[],int n)//普通冒泡排序
   
    {
   
    bool changed;
   
    do
   
    {
   
    changed=false;
   
    for(int i=1;i<n;i++)
   
    {
   
    if(strcmp(a[i],a[i-1])<0)
   
    {
   
    swap(a[i],a[i-1]);
   
    changed=true;
   
    }
   
    }
   
    --n;
   
    }
   
    while(changed);
   
    }
   
    //template <typename T>
   
    //void show(T t[],int n)
   
    template <typename T,int n>
   
    void show(T(&t)[n])
   
    {
   
    //int n=sizeof(t)/sizeof(t[0]);//算出t的个数
   
    for(int i=0;i<n;i++)
   
    cout《t[i]《‘ ';
   
    cout《endl;
   
    }
   
    template <typename T>
   
    void show(T t)
   
    {
   
    cout《t《endl;
   
    }
   
    int main()
   
    {
   
    int a ={6,7,8,3,2};
   
    sort(a,5);//函数模版会自动匹配,不需要显式指定类型
   
    show(a);
   
    double d=12.345;
   
    show(d);
   
    char c ={'b','f','k','d','a'};
   
    sort(c,5);
   
    show(c);
   
    const char* ca ={“fc”,“ca”,“ab”};
   
    sort(ca,3);
   
    show(ca);
   
    return 0;
   
    }
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇HDU 3339 In Acti.. 下一篇c++编写字符串编码类

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目