[槲寄生小记]函数模板与类模板(02)

题目: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)函数)

                ③输出函数

                ④输入函数(本题无要求)

  • 19
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值