4月25日作业

#include <iostream>
using namespace std;
template <typename T>
class myvector
{
private:
    T* begin; //指向头的指针
    T* end;   //指向数据的尾部的指针
    T* last;   //指向数据最大容量下标的指针
public:
    myvector(){}  //无参构造
    myvector(int a,const T &b)
    {
 
        begin=new T[a];
        for(int i=0;i<a;i++)
        {
            begin[i]=b;
        }
        last=begin+a;
        end=begin+a;
    } //有参构造
    ~myvector()   //析构函数
    {
        delete []begin;
        begin=end=last=nullptr;
 
 
    }
    myvector(const myvector &other)
    {
 
        T* temp=new T[other.last-other.begin];
        int a=other.last-other.begin;
        memcpy(temp,other.begin,sizeof(T)*a);
        delete []begin;
        begin=temp;
        end=begin+a;
        last=begin+a;
    }            //拷贝构造
    myvector &operator=(myvector &other)  //拷贝赋值
    {
        T* temp=new T[other.last-other.begin];
        int a=other.last-other.begin;
        memcpy(temp,other.begin,sizeof(T)*a);
        delete []begin;
        begin=temp;
        end=begin+a;
        last=begin+a;
        return *this;
    }
    T at(int a)    //at函数
    {
        if(a<0&&a>last-begin)
        {
            cout<<"下标超长"<<endl;
            throw(-1);
        }
        else
 
            return *(begin+a) ;
    }
    bool empty()   //判空
    {
        return begin==end;
    }
    bool full()     //判满
    {
        return end==last;
    }
    T front()       //访问第一个元素
    {
        return *begin;
    }
    T back()       //访问最后一个元素
    {
        return *end;
    }
     int size()     //容纳的元素个数
     {
        return last-begin+1;
     }
     void clear()     //清空
     {
        while(last!=begin)
        {
            pop_back();
        }
     }
     void expand()   //二倍扩容
     {
 
        T* temp=new T[2*(last-begin)];
        int s1=last-begin+1;
        int a=last-begin;
        memcpy(temp,begin,sizeof(T)*a);
        memcpy(temp,begin,sizeof (T)*s1);
        delete []begin;
        begin=temp;
        end=begin+a;
        last=begin+2*a;
 
     }
     void push_back(T other)  //将元素添加到尾部
     {
         if(end==last)
             {
                expand();
             }        //二倍扩容
         *(end++)=other;
 
 
     }
    void pop_back()
    {
        if(end==begin)
            cout<<"删除失败,容器为空";
        else
            end--;
    } //将尾部元素删除
    void show()
    {
        for(T*i=begin;i<=end;i++)
        {
            cout<<*i<<endl;
        }
    }
 
 
};
 
 
 
int main()
{
    myvector<int>s1(6,5);
    s1.push_back(3);
    s1.push_back(4);
    myvector<int>s2(s1);
    myvector<int>s3=s1;
    s1.show();
}

                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值