在C++语言中,已知一个有若干元素的数组array,使用函数模板分别求int型数组的最大值和double型数组的最大值,并编写一个类模板对数组元素进行排序、求和。
时间: 2024-01-22 12:17:35 浏览: 85
c++将数组名作为函数参数对数组元素进行相应的运算
5星 · 资源好评率100%
下面是对应的代码实现:
```c++
#include <iostream>
#include <algorithm>
using namespace std;
template<typename T> T maxElement(T *array, int n) {
T max = array[0];
for (int i = 1; i < n; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
template<typename T> class ArrayOperator {
public:
void sort(T *array, int n) {
sort(array, array+n);
}
T sum(T *array, int n) {
T result = 0;
for (int i = 0; i < n; i++) {
result += array[i];
}
return result;
}
};
int main() {
int arr1[] = {1, 5, 2, 6, 4};
double arr2[] = {1.2, 5.6, 2.3, 6.7, 4.1};
int n1 = sizeof(arr1) / sizeof(int);
int n2 = sizeof(arr2) / sizeof(double);
cout << "max of arr1: " << maxElement(arr1, n1) << endl;
cout << "max of arr2: " << maxElement(arr2, n2) << endl;
ArrayOperator<int> op1;
ArrayOperator<double> op2;
op1.sort(arr1, n1);
op2.sort(arr2, n2);
cout << "sorted arr1: ";
for (int i = 0; i < n1; i++) {
cout << arr1[i] << " ";
}
cout << endl << "sorted arr2: ";
for (int i = 0; i < n2; i++) {
cout << arr2[i] << " ";
}
cout << endl;
cout << "sum of arr1: " << op1.sum(arr1, n1) << endl;
cout << "sum of arr2: " << op2.sum(arr2, n2) << endl;
return 0;
}
```
输出结果为:
```
max of arr1: 6
max of arr2: 6.7
sorted arr1: 1 2 4 5 6
sorted arr2: 1.2 2.3 4.1 5.6 6.7
sum of arr1: 18
sum of arr2: 19.9
```
阅读全文