试用多态实现线性表

本文介绍了一种使用多态实现队列、串、堆栈等线性表的方法。通过定义一个通用模板`tcontainer`来抽象这些数据结构的共同特性,并以`tvector`为例展示如何具体实现一个动态数组。`tvector`能够进行push、pop等操作,并支持动态调整容量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*队列、串、堆栈都可以实现push,pop 测长等操作,
现在要求用多态去实现,就要建立一个线性表的共性模板;
*/


#include <iostream>
using namespace std;
template<typename t>


struct tcontainer
{
virtual void push(const t&) =0;
virtual void pop() =0;
virtual const t& begin() = 0;
virtual const t& end() =0;
virtual size_t size() =0;
};


template<typename t>
struct tvector : public tcontainer<t>
{
static const size_t step=100;//步长
tvector()
{
size =0;
//初始化向量实际大小
cap = step;
//向量内容为100
buf = 0;
//首地址,需动态分配内存
re_capacity(cap);
//此时buf为空,即要设置buf初始值,分配了100个元素空间

}
~tvector()
{
free(buf);
}


//调整容量
void re_capacity(size_t s)
{
if(!buf)
buf = (t*)malloc(sizeof(t) * s);
else
buf =(t*)realloc(buf,sizeof(t)*s);


}


//重写虚函数
virtual void push(const t& v)
{
if (size >= cap)
re_capacity(cap+=step);
buf[size++] = v;
}


virtual void pop()
{
if(size)
size--;
}


virtual const t& begin()
{
return buf[0];
}


virtual const t& end()
{
if (size)
return buf(size-1);
}


virtual size_t size()
{
return size;
}


const t& operator [] (size_t i)
{
if (i>=0 && i < size)
return buf[i];
}


private:
size_t size; //实际元素个数
size_t cap; //已分配的容量
t* buf; //首地址




};




int main()
{
tvector<int> v;
for (int i=0; i <1000; ++i)
v.push(i);


for (int i=0; i <1000; ++i)
cout << v[i] << endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值