C++模仿Vectors类

#include <iostream>

using namespace std;
template <typename T>

class Myvector
{
private:
    T* first;
    T* last;
    T* end;
public:
    //无参构造
    Myvector():first(0),last(0),end(0){}
    //有参构造
    Myvector(int n,const T& val):first(new T[n])
    {
        for(int i=0;i<n;i++)
        {
            first[i]=val;
        }
        last=end=first+n;
    }

    //析构
    ~Myvector()
    {
        delete []first;
    }

    //拷贝构造
    Myvector(const Myvector&F):first(new T[F.end-F.first])
    {
        last=first+(F.last-F.first);
        end=first+(F.end-F.first);
        memcpy(first,F.first,(last-first)*sizeof(T));
    }
    //拷贝赋值
    Myvector& operator=(const Myvector& F)
    {
        delete []first;
        first=new T[F.last-F.first];
        last=first+(F.last-F.first);
        end=first+(F.end-F.first);
        memcpy(first,F.first,(last-first)*sizeof(T));
        return *this;
    }

    //at
    T&at(int pos)
    {
        if(pos<0||pos>=last-first)
        {
            throw range_error("pos");
        }
        return first[pos];
    }

    //empty
    bool empty()
    {
        return  last==first?true:false;
    }

    //full
    bool full()
    {
        return last==end?true:false;
    }

    //size
    int size()
    {
        return last-first;
    }

    //clear
    void clear()
    {
        last==first;
    }

    //扩容
    void kuo()
    {
        Myvector temp;
        temp.first=new T[(end-first)*2];
        delete []first;
    }
    //push_back 在最后添加一个元素
    void push_back(const T&F)
    {
        if(full())
        {
            kuo();
        }
        *last++=F;

    }

    //pop_back 移出最后一个元素
    void pop_back()
    {
        if(empty())
            throw;
        last--;
    }

    //front
    T&front()
    {
        return *first;
    }

    //back
    T&back()
    {
        return *(end-1);
    }

    void show()
    {
        for(auto i=this->first;i<this->last;i++)
        {
            cout <<*i << " ";
        }
        cout<<endl;
    }

};


int main()
{
    Myvector<int> t(5,2);
    t.show();

    Myvector<int> T=t;
    T=t;
    T.show();
    T.push_back(2);
    T.show();
    T.pop_back();
    T.show();

    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值