动态数组写模板类

#include <iostream>
 
using namespace std;
template <typename T>//使用模板数据类型
class MYVCT
{
private:
    //动态数组定义三根指针分别指向首尾和使用量尾
    T* first;
    T* last;
    T* end;
public:
    MYVCT(int size=2){//有参构造赋值创造空间
        first=new T[size];//申请动态空间
        last =first;//首尾地址相同说明为空
        end=first+size;//空间尾指针
    }
    ~MYVCT(){//析构函数
        delete []first;
        first=last=end=nullptr;
    }
    MYVCT(const MYVCT &other)//拷贝构造
    {
        int len=other.last-other.first;
        int size=other.end-other.first;
        this->first=new T[size];//新对象的容量
        memcpy(this->first,other.first,len*sizeof (T));
    }
    //判空,为空返回turl,不为空返回false
    bool empty()
    {
        return this->first==this->last;
    }
    //判满,尾指针和空间尾指针重合时,为满
    bool full()
    {
        return this->last==this->end;
    }
    //扩容原则
    void greater()
    {
        //获取当前容器总容量
        int len=this->end-this->first;
        //定义一个新的指针对象申请2倍数据的动态堆空间
        T* temp=new T[len*2];
        //将之前的空间数据拷贝给给新的空间
        memcpy(temp,this->first,len*sizeof (T));
        //然后将之前空间给回收了
        delete []first;
        //再将当前指针指向当前
        this->first=temp;
        //更新其他指针
        last=first+len;
        end=first+2*len;
    }
 
    //尾插对象
    void tail_insert(const T m)
    {
        if(full())
        {
            greater();
        }
        *last=m;//last这一位属于有数据的下一位
        last++;
    }
    //实现尾删
    void pop_delete()
    {
        if(empty()==1)
        {
            cout<<"数据清空\n"<<endl;
            return;
        }
        --last;
    }
    //获取数组长度
    int my_size()
    {
        return end-first;
    }
    //获取使用的数组长度
    int my_len()
    {
        return last-first;
    }
    T& at(int dex)const
    {
 
        return *(first+dex);
    }
};
int main()
{
    MYVCT<int> v;
    for(int i=1; i<=20; i++)
    {
        v.tail_insert(i);
        cout<<v.my_size()<<endl;
    }
    for(int i=0; i<20; i++)
    {
        cout<<v.at(i)<<" ";
    }
    cout<<endl;
    cout << "Hello World!" << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值