您的位置:首页 > 编程语言 > C语言/C++

c++ 模板学习笔记:函数模板实现数组通用排序和遍历打印(权哥)

2013-11-24 22:19 976 查看
#include <algorithm>
#include <cstring>
#include <iostream>
using namespace std;

template <typename T>
void sort(T a[], int n)
{
for(int i=0; i<n-1; i++){
int min = i;
for(int j=i+1; j<n; j++)
if(a[j]<a[min])
min = j;
swap(a[min],a[i]);
}
}
template <typename T>
void sort(T* a[], int n)
{
for(int i=0; i<n-1; i++){
int min = i;
for(int j=i+1; j<n; j++)
if(*a[j]<*a[min])
min = j;
swap(a[min],a[i]);
}
}

template <>
void sort(const char* a[], int n)
{
for(int i=0; i<n-1; i++){
int min = i;
for(int j=i+1; j<n; j++)
if(strcmp(a[j],a[min])<0)
min = j;
swap(a[min],a[i]);
}
}
/*定义一个日期结构体*/
struct Date{
int y, m, d;
//Date(int y, int m, int d):y(y),m(m),d(d){}
};
/*小于号重载*/
bool operator<(const Date& a, const Date& b){
return (a.y<b.y||a.y==b.y&&(a.m<b.m||a.m==b.m&&a.d<b.d));
}
/*输出流重载*/
ostream& operator<<(ostream& o, const Date& d)
{
return o << d.y << '-' << d.m << '-' << d.d;
}
/*数组遍历打印,提供数组长度*/
template <class T>
void show(T a[], int n)
{
for(int i=0; i<n; i++)
cout << a[i] << ' ';
cout << endl;
}
/*template <typename T, int N>
//void show(T& t)
//{
//	int n = sizeof(t)/sizeof(t[0]);
//	for(int i=0; i<n; i++)
//		cout << t[i] << ' ';
//	cout << endl;
//}*/
/*数组遍历打印,只提供数组名*/
template <typename T, int N>
void show(T(&t)
)
{
for(int i=0; i<N; i++)
cout << t[i] << ' ';
cout << endl;
}
/*数组遍历打印,只提供数组名,而且数组是指针数组*/
template <typename T, int N>
void show(T*(&t)
)
{
for(int i=0; i<N; i++)
cout << *t[i] << ' ';
cout << endl;
}
/*打印单个指定类型的值*/
template <typename T>
void show(T data)
{
cout << data << endl;
}
int main()
{
double m=123.4;
show(m);
int a[5]={6,1,9,2,8};
double d[4]={3.3,5.5,2.2,1.6};
Date x[3]={{2010,9,30},{2010,9,9},{2010,8,8}};
sort(a,5);//a==>int*
//	sort(reinterpret_cast<int*>(d),4);
sort(d,4);
sort(x,3);
show(a,5);show(d,4);show(x,3);
show(a);show(d);show(x);
const char* s[3]={"furong","quange","chunge"};
sort(s,3);
show(s);
int* ap[4]={new int(5),new int(2),new int(9),new int(8)};
double* bp[3]={new double(3.3),new double(5.5),new double(2.2)};
sort(ap,4);sort(bp,3);
show(ap);show(bp);
}
/*输出:
123.4
1 2 6 8 9
1.6 2.2 3.3 5.5
2010-8-8 2010-9-9 2010-9-30
1 2 6 8 9
1.6 2.2 3.3 5.5
2010-8-8 2010-9-9 2010-9-30
c f q
2 5 8 9
2.2 3.3 5.5
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  CC++ 模板
相关文章推荐