多态实现线性表(队列、串、堆栈)

来源:互联网 发布:济南js复合保温模板 编辑:程序博客网 时间:2024/06/05 14:52

说明:
建立一个线性表的共性模板,来实现插入、删除、测长等操作。

#include <iostream>  #include <iomanip>  using namespace std;template<class T>class tcontainer{public:     void push(T &a) ;     void pop(void);     int size(void) ;};template<class T>class tvector : public tcontainer<T>{public:    static const int step = 100;    tvector(){        _size = 0;//初始化向量实际大小        _cap = step;//向量容器为100        _buf = 0;//首地址,需要动态分配内存        re_capacity(_cap);        //此时buf为空,即要设置buf初始值    };    ~tvector(){        if (_buf)            free(_buf);    };    //调整容量     void re_capacity(int s){        if (_buf)            _buf = (T *)realloc(_buf, s*sizeof(T));        else{            _buf = (T*)malloc(sizeof(T)*s);        }    };     void push(T &a){        _size++;        if (_size>_cap)            re_capacity(_cap += step);        _buf[_size - 1] = a;    }     void pop(void){        if (_size)            _size--;    }     int size(void){        return _size;    }    const T &operator[](int index){        if (index >= 0 && index<_size)            return *(_buf + index);    }private:    size_t _cap;//实际元素个数    size_t _size;//已分配的容量    T* _buf;//首地址};int main(int argc, char *argv[]){    tvector<int> v;    for (int i = 0; i<300; ++i)        v.push(i);    for (int i = 1; i < 301; ++i)        (i % 15 == 0) ? (cout << v[i - 1] << endl) : (cout << setw(3) << v[i - 1] << " ");        /*cout << v[i-1] << endl;*/    system("pause");    return 0;}
1 0
原创粉丝点击