C++primer plus第六版课后编程题答案8.6
8.6
#include <iostream>
#include <string>
using namespace std;
template <typename AnyType>
AnyType maxn(AnyType arr[],int size)//模板类
{
AnyType max=arr[0];
for(int i=0;i<size;i++)
{
if(arr[i]>max)
max=arr[i];
}
return max;
};
template <>string maxn<string>(string arr[],int size)//具体化
{
int max=0;//用于记录最大的字符串长度
int temp=0;//用于记录字符串长度
int place=0;//用于记录所在位置
for(int i=0;i<size;i++)
{
temp=arr[i].length();
if(temp>max)
{
max=temp;
place=i;//记录字符串所在位置
}
}
//return arr[max];
return arr[place];
};
void main86()
{
int a[6]={10,3,50,45,33,60};
double b[4]={4.5,6.7,2.5,3.1};
string c[5]={"you","heheshui","oo","tianxia","end"};
cout<<"The amax is "<<maxn(a,6)<<endl;
cout<<"The bmax is "<<maxn(b,4)<<endl;
cout<<"The cmax is "<<maxn(c,5)<<endl;
system("pause");
}

浙公网安备 33010602011771号