__________________________________________________________________________________________________________________________________________
下面的是正确的,后面的有点小问题。
#include <iostream>
#include <cstring>
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 <> char *maxn<char *>(char *a[],int n)
{
char *pa=a[0];
for (int i=1;i<n;i++)
{
int temp=strlen(pa);
if(temp<strlen(a[i]))
pa=a[i];
else pa=pa;
}
return pa;
}
int main()
{
int a[6]={10,3,50,45,33,60};
double b[4]={4.5,6.7,2.5,3.1};
char *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;
return 0;
}
感谢网友的指出。
-------------2014.10.8
—————————————————————————————————————————————————————————————————————————————
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");
}