13
2012
10

linux下练习 c++ 函数模版例子

code:

//函数模版使用
//函数模版标准不支持参数默认值
#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[5]={6,7,8,3,2};
sort(a,5);//函数模版会自动匹配,不需要显式指定类型
show(a);
double d=12.345;
show(d);
char c[5]={'b','f','k','d','a'};
sort(c,5);
show(c);
const char* ca[3]={"fc","ca","ab"};
sort(ca,3);
show(ca);
return 0;
}




版权声明:
作者:真爱无限 出处:http://www.pukuimin.top 本文为博主原创文章版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接.
« 上一篇下一篇 »

相关文章:

评论列表:

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。