第一个T函数
#include
#include "stdlib.h"
#include
using namespace std;
template T co(T A[],int n);
template <> char* co(char* a[],int y);
int main()
{
int d[5]={50,10,28,5,100};
int p;
p = co(d,5);
cout << p << "/n";
char* dd[5] ={"lbsjs","jkdjkalssdjkljkl","jkkj","lihui","gougou"};
char* dw=co(dd,5);
cout << dw <<"/n";
system("pause");
return 0;
}
template
T co(T a[],int n)
{
T u;
u = a[0];
for(int i = 1;i < n;i++)
{
if (a[i] > u)
u = a[i];
}
return u;
}
template <> char* co(char* a[],int y)
{
int q,b;
q = strlen(a[0]) + 1;
for(int i = 1;i < y;i++)
{
b = strlen(a[i]) + 1;
if (b > q)
q = b;
}
for(int i = 0;i < y;i++)
{
if (strlen(a[i]) + 1 == q)
return a[i];
}
}
模板函数求数组最大值示例
博客展示了一段C++代码,定义了模板函数co用于求数组中的最大值。对于不同数据类型的数组,函数有不同的处理方式。代码中分别对整数数组和字符指针数组调用该函数,并输出结果,还使用了system(\pause\)暂停程序。

被折叠的 条评论
为什么被折叠?



