• 动态数组写模板类


    #include 
     
    
    using namespace std;
    template //使用模板数据类型
    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"< 
    
                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 v;
        for(int i=1; i<=20; i++)
        {
            v.tail_insert(i);
            cout< 
    
        }
        for(int i=0; i<20; i++)
        {
            cout< 
    
        }
        cout< 
    
        cout << "Hello World!" << endl;
        return 0;
    }
  • 相关阅读:
    AGC034E Complete Compress
    MAYA粒子基础_场
    mysql配置提高数据插入效率
    phpstorm安装xdebug(phpstudy环境下)成功运行
    「BUAA OO Pre」 Pre 2总结回顾概览
    UVA208 消防车 Firetruck
    Mybatis小记
    G2024-04-24 开源项目日报 Top10
    VBA实现全文件快速替换
    LeetCode0461.汉明距离 Go语言AC笔记
  • 原文地址:https://blog.csdn.net/weixin_47440242/article/details/126613829