编写一个求任意类型数组中最大值和最小值元素的程序,要求将求最大元素和最小元素的函数设计成函数模板
#include<iostream>
#include<iomanip>
using namespace std;
const int n=5;
template<typename t>
t max(t p[],int n)
{
t max=p[0];
for(int j=1;j<n;j++)
{
if(p[j]>max)
{
max=p[j];
}
}
return max;
}
template<typename t>
t min(t *p,int n)
{
t min=p[0];
for(int j=1;j<n;j++)
{
if(p[j]<min)
{
min=p[j];
}
}
return min;
}
template<typename t>
void show(t p[])
{
for(int j=0;j<n;j++)
cout<<setw(5)<<p[j];
cout<<endl;
}
int main()
{
int p[n]={1,2,3,4,5};
double h[n]={34,2,5,6,7};
int a;
double b;
a = max(p,5);
b = min(h,5);
show<int>(p);
cout<<"该数组的最大值:"<<a<<endl;
show<double>(h);
cout<<"该数组的最小值:"<<b<<endl;
system("pause");
return 0;
}