(求数组中的最大值)设计一个通用函数,能求出数组中的最大元素,函数有两个参数,一个是通用类型数组,另一个是数组的大小。用int、double、string数组测试这个函数。
我表示不是很喜欢通用的这种类型的题目,我觉得这样的通用反而局限性更大,非常麻烦,所以最好还是具体问题具体问题具体分析。下面上代码:
(以下代码在VS2017上编译通过)
#include "pch.h"
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
template <typename T>
void FindMax(T shuzu[], const int size)
{
sort(shuzu, shuzu + size);
cout << "最大值是:" << shuzu[size - 1] << endl;
}
int main()
{
int a[5] = { 1,3,5,7,2 };
double b[5] = { 1.2,2.4,3.6,10.24,20.48 };
string c[5] = { "abc","DEF","996DIEOUTFROMECHINA" ,"GetoutofChina","SupportCPC"};
const int n = 5;
FindMax(a, n);
FindMax(b, n);
FindMax(c, n);
return 0;
}