已知一个有若干元素的数组array,使用函数模板分别求int型数组的最大值和double型数组的最大值,并编写一个类模板对数组元素进行排序、求和。
时间: 2024-01-22 22:17:39 浏览: 96
下面是代码示例:
```c++
#include <iostream>
#include <algorithm>
using namespace std;
template<typename T>
T get_max(T arr[], int size) {
T max_val = arr[0];
for(int i=1; i<size; i++) {
if(arr[i] > max_val) {
max_val = arr[i];
}
}
return max_val;
}
template<typename T>
class Array {
private:
T* data;
int size;
public:
Array(T arr[], int size) {
this->size = size;
this->data = new T[size];
for(int i=0; i<size; i++) {
this->data[i] = arr[i];
}
}
void sort() {
std::sort(data, data+size);
}
T sum() {
T sum_val = 0;
for(int i=0; i<size; i++) {
sum_val += data[i];
}
return sum_val;
}
void display() {
for(int i=0; i<size; i++) {
cout << data[i] << " ";
}
cout << endl;
}
};
int main() {
int int_arr[] = {1, 5, 3, 2, 6};
double double_arr[] = {3.14, 2.71, 1.41, 2.0, 0.618};
int int_max = get_max(int_arr, 5);
double double_max = get_max(double_arr, 5);
cout << "int array max: " << int_max << endl;
cout << "double array max: " << double_max << endl;
Array<int> int_array(int_arr, 5);
Array<double> double_array(double_arr, 5);
cout << "before sort: " << endl;
int_array.display();
int_array.sort();
cout << "after sort: " << endl;
int_array.display();
cout << "int array sum: " << int_array.sum() << endl;
cout << "before sort: " << endl;
double_array.display();
double_array.sort();
cout << "after sort: " << endl;
double_array.display();
cout << "double array sum: " << double_array.sum() << endl;
return 0;
}
```
输出结果如下:
```
int array max: 6
double array max: 3.14
before sort:
1 5 3 2 6
after sort:
1 2 3 5 6
int array sum: 17
before sort:
3.14 2.71 1.41 2 0.618
after sort:
0.618 1.41 2 2.71 3.14
double array sum: 10.859
```
可以看到,我们成功地使用函数模板求出了int型数组和double型数组的最大值,并且使用类模板对数组元素进行了排序和求和。
阅读全文