华清远见上海中心22071班--10.10作业

#include <iostream>
#include <cstring>

using namespace std;
template<typename T>
class my_vector
{
private:
    T *front;
    T *end;
    T *last;
public:
    my_vector()//无参构造
    {
        front = new T[10];
        end = front;
        last = front+9;
        cout<<"无参构造"<<endl;
    }
    my_vector(int a,const T &val)//有参构造
    {
        front = new T[10];
        end = front;
        last = front+9;
        for(int i=0;i<a;i++)
        {
            *end=val;
            end++;
        }
        cout<<"有参构造"<<endl;
    }
    ~my_vector()//析构
    {
        delete []front;
    }
    bool my_empty()//判空
    {
        return front==end;
    }
    int my_capacity()  //容量
    {
       return last-front;
    }
    void cap_double()//容量倍增
    {
        int n = my_capacity();
        T *temp = front;
        front = new T[2*n+1];
        memcpy(front,temp,n*sizeof(T));
        end=front+n;
        last=front+2*n;
    }
    int my_size()  //已容纳元素个数
    {
        return end-front;
    }
    void mypush_back(const T &val)//尾插
    {
        *end=val;
        end++;
        if(end==last)
            cap_double();
    }
    void mypop_back() //尾删
    {
        if(my_empty())
        {
            cout<<"容器为空,无元素可删除"<<endl;
            return ;
        }
        end--;
    }
    T &get_element(int pos)//获取元素
    {
        if(pos<my_size())
        {
            return front[pos];
        }
        else
            cout<<"该位置元素为空"<<endl;
    }
    T &get_first()  //获取首个元素
    {
        if(!my_empty())
            return front[0];
        cout<<"容器为空"<<endl;
    }
    T &get_back()   //获取末尾元素
    {
        if(!my_empty())
            return *(end-1);
        cout<<"容器为空"<<endl;
    }
    void my_clear()    //清空元素
    {
        end=front;
    }
    void show()
    {
        for(int i=0;i<my_size();i++)
        {
            cout<<front[i]<<"   "<<endl;
        }

    }
};

int main()
{
    my_vector<int> v1(5,5);
    v1.mypush_back(6);
    v1.mypush_back(6);
    v1.mypush_back(6);
    v1.mypush_back(6);

    cout<<v1.my_size()<<endl;
    cout<<v1.my_capacity()<<endl;
    cout<<v1.get_first()<<endl;
    cout<<v1.get_back()<<endl;
    v1.show();

    return 0;
}

执行现象:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值