问题描述及代码:
/*
*copyright (c) 2016,烟台大学计算机学院
*All rights reserved.
*文件名称:hellow.cpp
*作者:田甜
*完成日期:2016年5月28日
*版本号:v1.0
*
*问题描述:
void Sort(int a[],int size);
void Sort(double a[],int size);函数模板的两个实例,其功能是将数组a中的前size个元素按从小到大顺序排列。试设计这个函数模板。
*输入描述:///
*程序输出:*/
#include <iostream>
using namespace std;
template<class T>
void sort(T set[],int size)
{
int i,j;
T temp;
for(i=1;i<size;i++)
for(j=size-1;j>=i;j--)
if(set[j-1]>set[j])
{
temp=set[j-1];
set[j-1]=set[j];
set[j]=temp;
}
}
int main()
{
int i;
int a[]={4,7,2,3,4};
char b[]={'c','w','r','a','t'};
sort(a,5);
sort(b,5);
for(i=0;i<5;i++)
cout<<a[i]<<" ";
cout<<endl;
for(i=0;i<5;i++)
cout<<b[i]<<" ";
cout<<endl;
return 0;
}
运行结果:
心得体会:
template<class T>
模板函数前需要写的,T是一种类型,在函数的任何地方都可以使用,就像int、double 之类的