题目:2023-2024(1)C++程序设计实验6-by Lyx - 函数模板与类模板
The green eyes are inherited from my mother. Although I did not grow into a lady of the upper class as she wished ... ... I thank my mother for everything she left.
绿色的眼睛遗传自我的母亲。虽然我没有如她所愿地成为上流社会的淑女,但是我感谢母亲留给我的一切。
一, 题目要求:
1.总体要求
利用类模板实现对整型数组和字符数组的排序。
2.输入形式
【样例输入】
无需手动输入
3.输出形式
【样例输出】
before sort: 3 6 2 1 4
after sort: 1 2 3 4 6
before sort: 3.1 1.2 4.5 1.1 0.2
after sort: 0.2 1.1 1.2 3.1 4.5
before sort: s d a y t
after sort: a d s t y
二,题目解析:
1.答案
#include <iostream>
using namespace std;
template <typename T>
class SortArray {
private:
T* arr;
int size;
public:
SortArray(T* array, int length) {
arr = new T[length];
size = length;
for (int i = 0; i < length; i++) {
arr[i] = array[i];
}
}
void sort() {
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
T temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void display() {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
};
int main() {
int intArr[] = {3, 6, 2, 1, 4};
SortArray<int> intSort(intArr, 5);
cout<<"before sort: ";
intSort.display();
intSort.sort();
cout<<"after sort: ";
intSort.display();
float floatArr[] = {3.1, 1.2, 4.5, 1.1,0.2};
SortArray<float> floatSort(floatArr, 5);
cout<<"before sort: ";
floatSort.display();
floatSort.sort();
cout<<"after sort: ";
floatSort.display();
char charArr[] = {'s','d','a','y','t'};
SortArray<char> charSort(charArr, 5);
cout<<"before sort: ";
charSort.display();
charSort.sort();
cout<<"after sort: ";
charSort.display();
return 0;
}
2.分步解析
1.需要定义的类模板
①SortArray类
2.类模板需要的函数
①交换函数(自定义mySort(a,b)函数/swap(a,b)函数)
②排序函数(自定义mySort(a,b)函数/sort(a,b)函数)
③输出函数
④输入函数(本题无要求)