函数模板的应用。

看了普拉达的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;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值