2.编写一个使用类模板对数组进行排序、元素查找,以及求元素累加和的程序。类 模板中包括数组成员,以对数组进行排序、元素查找、求元素累加和等功能的成员 函数。类模板的声明参考如下: const int SIZE=10; template < class T> class Array { private: T a[SIZE]; public: Array0; void sort(); int find(T k); T sumO; void print();
时间: 2023-06-27 22:01:21 浏览: 257
下面是使用类模板对数组进行排序、元素查找以及求元素累加和的程序:
```c++
#include <iostream>
using namespace std;
const int SIZE = 10;
template <class T>
class Array {
private:
T a[SIZE];
public:
Array() {
for(int i = 0; i < SIZE; i++) {
cout << "Enter element " << i+1 << ": ";
cin >> a[i];
}
}
void sort() {
for(int i = 0; i < SIZE-1; i++) {
for(int j = i+1; j < SIZE; j++) {
if(a[i] > a[j]) {
T temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
int find(T k) {
for(int i = 0; i < SIZE; i++) {
if(a[i] == k) {
return i;
}
}
return -1;
}
T sum() {
T sum = 0;
for(int i = 0; i < SIZE; i++) {
sum += a[i];
}
return sum;
}
void print() {
for(int i = 0; i < SIZE; i++) {
cout << a[i] << " ";
}
cout << endl;
}
};
int main() {
cout << "Enter 10 integers:" << endl;
Array<int> arr;
cout << "Original array: ";
arr.print();
arr.sort();
cout << "Sorted array: ";
arr.print();
int num;
cout << "Enter number to find: ";
cin >> num;
int index = arr.find(num);
if(index != -1) {
cout << num << " found at index " << index << endl;
} else {
cout << num << " not found" << endl;
}
cout << "Sum of elements: " << arr.sum() << endl;
return 0;
}
```
运行示例:
```
Enter 10 integers:
Enter element 1: 8
Enter element 2: 5
Enter element 3: 2
Enter element 4: 7
Enter element 5: 4
Enter element 6: 1
Enter element 7: 9
Enter element 8: 3
Enter element 9: 6
Enter element 10: 0
Original array: 8 5 2 7 4 1 9 3 6 0
Sorted array: 0 1 2 3 4 5 6 7 8 9
Enter number to find: 5
5 found at index 5
Sum of elements: 45
```
阅读全文