定义一个类模板:
template
class Array
{
……
};
具有对数组元素进行排序和求和的功能。在主函数中,从键盘读入若干int型、double型和char型数据,分别对整型数组、双精度数组和字符数组完成所要求的操作。
输入格式:
每行为一个操作,每行的第一个数字为元素类型,1为int元素,2为double元素,3为char类型。若为int型元素,接着输入int数据,若为double元素,接着输入double数据,若为char型元素,三种类型的元素均以0结束。输入-1时表示全体输入结束。
输出格式:
int型、double型数据输出相应数组排序后的数据及数组的和,char型数据输出排序后的数组元素。
输入样例:
在这里给出一组输入。例如:
1 2 3 4 5 6 0
3 a s d e r q w t 0
2 1.1 2.3 5.6 7.8 0
-1
输出样例:
在这里给出相应的输出。例如:
[2,3,4,5,6]
20
[a,d,e,q,r,s,t,w]
[1.1,2.3,5.6,7.8]
16.8
#include <iostream>
using namespace std;
template<typename T>
class Array
{
private:
int len;//私有成员 长度
T* array;//私有成员 自定义类型的一个 指针a
public:
Array(T* a, int length) :array(a), len(length) {}
void Sort()
{
bool tt = true;
for (int i = 0; i < len - 1 && tt; i++)
{
tt = false;
for (int j = 0; j < len - i - 1; j++)
{
if (array[j] > array[j + 1])
{
T temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
tt = true;
}
}
}
cout << "[";
for (int i = 0; i < len; i++) {
cout << array[i];
if (i == len - 1)
cout << "]" << endl;
else cout << ",";
}
}
void sumarray() {
T sum = 0;
for (int i = 0; i < len; i++) {
sum += array[i];
}
cout << sum << endl;
}
};
int main(){
int ch = 0;
int i = 0;
while (cin >> ch) {
if (ch == -1)
break;
else if (ch == 1) {
int n = 0;
int a1[999];
for (int i = 0;; i++) {
cin >> a1[i];
if (a1[i] == 0)
break;
n++;
}
Array<int>array(a1, n);
array.Sort();
array.sumarray();
}
else if (ch == 2) {
int n = 0;
double a2[999];
for (int i = 0;; i++) {
cin >> a2[i];
if (a2[i] == 0)
break;
n++;
}
Array<double>array(a2, n);
array.Sort();
array.sumarray();
}
else if (ch == 3) {
int n = 0;
char a3[999];
for (int i = 0;; i++) {
cin >> a3[i];
if (a3[i] == '0')
break;
n++;
}
Array<char>array(a3, n);
array.Sort();
}
}
return 0;
}