类模板实现数组排序

来源:互联网 发布:单片机助手 编辑:程序博客网 时间:2024/06/15 00:13

先写出单个类型排序类,再在此基础上变成类模板。

/*用类模板来完成下列工作:(1) 定义一个数组类模板,能对数组进行排序及求最大元素值,并重载“[ ]”运算符。(要求同时处理“整型数组、实型数组、字符数组”);(2) 定义一个栈类模板,实现其入栈和出栈操作。*/#include<iostream>using namespace std;template <class numtype>class Num{private:    numtype a[10];    int number;    numtype Max;public:    Num(numtype *p, int geshu);    void sort();    void show();    numtype operator[](int);};template <class numtype>Num<numtype>::Num(numtype *p, int geshu){    number = geshu;    for (int i = 0; i < number; i++)    {        a[i] = *(p + i);    }}template <class numtype>void Num<numtype>::sort(){    for (int i = 0; i < number; i++)    {        for (int j = i + 1; j < number; j++)        {            if (a[i] < a[j])            {                numtype swap;                swap = a[i];                a[i] = a[j];                a[j] = swap;            }        }    }    Max = a[0];}template <class numtype>void Num<numtype>::show(){    cout << "排序后的数组为" << endl;    for (int i = 0; i < number; i++)    {        cout << a[i] << '\t';    }    cout << endl;}template <class numtype>numtype Num<numtype>::operator[](int i){    if (i >= 0)        return a[i];    if (i < 0)        return Max;}int main(){    int aa[5] = { 1,2,3,4,5 };    char bb[5] = "abcd";    double cc[5] = { 1.2,2.1,4.5,8.5,3.4 };    Num <int>test1(aa, 5);   //要这样声明    Num <char>test2(bb, 5);    Num <double>test3(cc, 5);    test1.sort();    test1.show();    cout << "最大的为:" << endl;    cout << test1[-1] << endl;    test2.sort();    test2.show();    cout << "最大的为:" << endl;    cout << test2[-1] << endl;    test3.sort();    test3.show();    cout << "最大的为:" << endl;    cout << test3[-1] << endl;    system("pause");    return 0;}
原创粉丝点击