编写模板函数max5(),它将一个包含5个T类型元素的数组作为参数,并返回数组中最大的元素(由于长度固定,因此可以在循环中使用硬编码,而不必通过参数来传递)。在一个程序中使用该函数,将T替换为一个包含5个int值的数组和一个包含5个dowble值的数组,以测试该函数。
#include <iostream> using namespace std; template<class T> T max5(T st[]); int main() { int arr[5]={1,2,3,4,5}; double arr_d[5]={19.6,13,19.8,100.8,98.4}; cout<<"The max Element of int array:"<<max5(arr)<<endl; cout<<"The max Element of int array:"<<max5(arr_d)<<endl; system("pause"); return 0; } template<class T> T max5(T st[]) { T max=st[0]; for (int i = 0; i < 5; i++) { if(st[i]>max) max=st[i]; } return max; }
#include<iostream> using namespace std; template<class T> T max5(T arr[5]) { T obj1=arr[0]; for(int i=0;i<5;i++) { if(arr[i]>obj1) { obj1=arr[i]; } } return obj1; } void main() { int arr1[5]={1,2,3,4,5}; double arr2[5]={1.0,2.0,3.0,4.0,5.0}; int m1=max5<int>(arr1); double m2=max5<double>(arr2); cout<<m1<<endl<<m2<<endl; }