c++ 函数模板求数组中的最大值

Problem Description
设计一个函数模板,能够从int、char、float、double、long等类型的数组中找出最大值元素。
//你的代码将嵌在这里
int main()
{
int ai[6] = { 10,21,-31,13,6,0 };
char ac[4] = { ‘a’,‘U’,’*’,‘8’ };
float af[5] = { 1.2F,6.32F,-6.2F,0.2F,92.3F };
double ad[3] = { 3.2,95.123,-3.12 };
long al[4] = { 32L,21L,909L,-62L };
cout << max<int,6>(ai) << endl;
cout << max<char, 4>(ac) << endl;
cout << max<float, 5>(af) << endl;
cout << max<double, 3>(ad) << endl;
cout << max<long, 4>(al) << endl;
return 0;
}

Sample Output
21
a
92.3
95.123
909

#include <iostream>
using namespace std;

template<typename T,int t>//t是数组长度

T max(T b[t])//未知数组类型
{
    T temp = b[0];//从第一个数开始比较,记录第一个数的值
    for (int i = 0; i < t; i++)
    {
        if ( temp < b[i])
        {
            temp = b[i];//让变量继承最大值继续比较
        }    
    }
    return temp;
}

int main()
{
    int ai[6] = { 10,21,-31,13,6,0 };
    char ac[4] = { 'a','U','*','8' };
    float af[5] = { 1.2F,6.32F,-6.2F,0.2F,92.3F };
    double ad[3] = { 3.2,95.123,-3.12 };
    long al[4] = { 32L,21L,909L,-62L };
    cout << max<int, 6>(ai) << endl;//<>号中的内容对应第四行<>中的内容
    cout << max<char, 4>(ac) << endl;
    cout << max<float, 5>(af) << endl;
    cout << max<double, 3>(ad) << endl;
    cout << max<long, 4>(al) << endl;
    return 0;
}


版权声明:本文为dimrhyme原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。