看了普拉达的c++书,然后看到第8章的编程习题,自己编了一个程序,主要实现以下功能:利用函数模板知识,编写一个求得最大值得函数模板,对于输入的double型或者int型都能够适用,然后再编写一个重载的具体化模板,实现,输入有限个字符串,并且以指针字符串和指针数量,作为形参,并且返回最长字符串的地址。
#include<iostream>
#include<cstring>
#include<stdlib.h>
using namespace std;
template <typename T>
T Max5(T arr[], int n) {
T max = arr[0];
for (int i = 1; i < n; i++)
{
if(arr[i] > max)
max = arr[i];
}
return (max);
}
template <>char *Max5(char *a[], int n) {
int max = -1;
char *p = NULL;
for (int i = 0; i < n; i++)
{
if (int(strlen(a[i])) > max)
{
max = strlen(a[i]);
p = a[i];
}
}
return p;
}
int main() {
int a[5];double e[5];
cout << "input 5 intnumbers\n";
for(int i=0;i<5;i++)
{
cin >> a[i];
}
int c=Max5(a, 5);
cout << "the max is "<<c << endl;
cout << "input 5 doublenumbers\n";
for(int i=0;i<5;i++)
{
cin >> e[i];
}
double d = Max5(e, 5);
cout << "the max is" << d << endl;
cout << "please input five zifuchuan:\n";
char *b[5];
for(int i=0;i<5;i++)
{
//char *b[i] = new char[20];
b[i]=(char*)malloc(1024);
cin >> b[i];
}
cout <<"the max zifuchuan is:"<< Max5(b, 5) << endl;
return 0;
}