您的位置:首页 > 其它

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

2017-04-18 16:05 351 查看
说明:

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

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: