编写一个函数模板largest_element()用来计算数组的最大值。数组元素可以是任意数据类型。该函数有两个参数,第一个数数组名,第二个是数组元素的个数,返回值类型为数组元素类型。 【输入形式】输入有3行,每行数据的第1个数n, 表示数组元素的个数,后面跟n个数组元素(n<=10),第一行元素为int类型,第二行为double类型,第三行为char类型。 【输出形式】输出有3行,每行输出对应数组的最大元素值 【样例输入】 5 3 7 1 9 6 4 5.7 8.9 2.4 3.1 6 fHyAxk 【样例输出】 9 8.9 y
时间: 2024-01-21 14:17:31 浏览: 80
以下是该函数的函数模板实现:
```c++
#include <iostream>
using namespace std;
// 函数模板:计算数组的最大值
template<typename T>
T largest_element(T arr[], int n) {
T max_val = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > max_val) {
max_val = arr[i];
}
}
return max_val;
}
int main() {
// 输入三个数组,分别为 int、double、char 类型
int n1, n2, n3;
cin >> n1;
int arr1[n1];
for (int i = 0; i < n1; i++) {
cin >> arr1[i];
}
cin >> n2;
double arr2[n2];
for (int i = 0; i < n2; i++) {
cin >> arr2[i];
}
cin >> n3;
char arr3[n3];
for (int i = 0; i < n3; i++) {
cin >> arr3[i];
}
// 计算三个数组的最大值并输出
cout << largest_element<int>(arr1, n1) << endl;
cout << largest_element<double>(arr2, n2) << endl;
cout << largest_element<char>(arr3, n3) << endl;
return 0;
}
```
其中,函数模板 `largest_element()` 使用了模板类型 `T`,表示数组元素的类型。在函数模板中,我们使用 `T max_val = arr[0];` 将数组的第一个元素设为当前的最大值,然后遍历整个数组,如果遇到比当前最大值还要大的元素,就将其设为新的最大值。最终返回最大值即可。
在主函数中,我们先分别输入三个数组,然后调用 `largest_element()` 函数模板计算三个数组的最大值,分别输出即可。注意在调用函数模板时,需要显示指定模板类型,例如 `largest_element<int>(arr1, n1)` 表示使用 `int` 类型计算 `arr1` 数组的最大值。
阅读全文
相关推荐
![text/x-c](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)