qfedu-cpp-level/day6/homework/h2.cpp

30 lines
839 B
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 编写一个模板函数 maxValueInArray接受一个数组和数组的大小并返回数组中的最大值。
//【提示】T maxValueInArray(T arr[], int size)
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
template <typename T>
T maxValueInArray(T arr[], int size)
{
T max = arr[0];
for (int i = 1; i < size; i++)
if (arr[i] > max)
max = arr[i];
return max;
}
int main()
{
int arr1[] = {1, 3, 5, 7, 9, 2, 4, 6, 8, 0};
char arr2[] = {'a', 'c', 'e', 'G', 'I', 'b', 'd', 'f', 'h', 'j'};
int size1 = sizeof(arr1) / sizeof(arr1[0]);
int size2 = sizeof(arr2) / sizeof(arr2[0]);
cout << "arr1 的最大值是: " << maxValueInArray(arr1, size1) << endl;
cout << "arr2 的最大值是: " << maxValueInArray(arr2, size2) << endl;
return 0;
}