编写一个求任意类型数组中最大元素和最小元素的程序,要求将求最大元素和最小元素的函数设计成函数模板。
时间: 2024-05-07 22:23:33 浏览: 149
下面是一个求任意类型数组中最大元素和最小元素的程序,其中`find_max`和`find_min`函数被设计成函数模板:
```c++
#include <iostream>
template <typename T>
T find_max(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 <typename T>
T find_min(T arr[], int n) {
T min = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] < min) {
min = arr[i];
}
}
return min;
}
int main() {
int int_arr[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3};
double double_arr[] = {3.14, 2.71, 1.41, 1.62, 1.73};
char char_arr[] = {'h', 'e', 'l', 'l', 'o'};
int int_max = find_max(int_arr, 10);
int int_min = find_min(int_arr, 10);
double double_max = find_max(double_arr, 5);
double double_min = find_min(double_arr, 5);
char char_max = find_max(char_arr, 5);
char char_min = find_min(char_arr, 5);
std::cout << "Max of int_arr: " << int_max << std::endl;
std::cout << "Min of int_arr: " << int_min << std::endl;
std::cout << "Max of double_arr: " << double_max << std::endl;
std::cout << "Min of double_arr: " << double_min << std::endl;
std::cout << "Max of char_arr: " << char_max << std::endl;
std::cout << "Min of char_arr: " << char_min << std::endl;
return 0;
}
```
输出结果:
```
Max of int_arr: 9
Min of int_arr: 1
Max of double_arr: 3.14
Min of double_arr: 1.41
Max of char_arr: o
Min of char_arr: e
```
阅读全文