编写一个求任意类型数组中最大元素和最小元素的程序,要求将求最大元素和最小元素的函数设计成函数模板
时间: 2024-05-07 07:20:05 浏览: 77
以下是使用函数模板求任意类型数组中最大元素和最小元素的程序:
```cpp
#include <iostream>
template<typename T>
T getMax(T arr[], int size) {
T max = arr[0];
for(int i = 1; i < size; i++) {
if(arr[i] > max) {
max = arr[i];
}
}
return max;
}
template<typename T>
T getMin(T arr[], int size) {
T min = arr[0];
for(int i = 1; i < size; i++) {
if(arr[i] < min) {
min = arr[i];
}
}
return min;
}
int main() {
int intArr[] = {1, 2, 3, 4, 5};
double doubleArr[] = {1.1, 2.2, 3.3, 4.4, 5.5};
char charArr[] = {'a', 'b', 'c', 'd', 'e'};
std::cout << "Max of int array: " << getMax(intArr, 5) << std::endl;
std::cout << "Min of int array: " << getMin(intArr, 5) << std::endl;
std::cout << "Max of double array: " << getMax(doubleArr, 5) << std::endl;
std::cout << "Min of double array: " << getMin(doubleArr, 5) << std::endl;
std::cout << "Max of char array: " << getMax(charArr, 5) << std::endl;
std::cout << "Min of char array: " << getMin(charArr, 5) << std::endl;
return 0;
}
```
输出:
```
Max of int array: 5
Min of int array: 1
Max of double array: 5.5
Min of double array: 1.1
Max of char array: e
Min of char array: a
```
阅读全文