手动实现My_vector

要求:

构造函数 析构函数 拷贝构造 拷贝赋值 at() empty() full() front() back() size() clear() expand() 二倍扩容函数 push_back() pop_back()

代码如下:

#include <iostream>

using namespace std;

template <typename T>
class Myvector
{
private:
    T * first;
    T * last;
    T * end;

public:
    //构造函数
    Myvector(int size = 4)
    {
        first = new T [size];
        last = first;
        end = first+size;
    }

    //析构函数
    ~Myvector()
    {
        delete []first;
        first = nullptr;
    }

    //拷贝构造
    Myvector (const Myvector &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));
        this->last = this->first+len;
        this->end = this->first+size;

    }


    //扩容
    void expand()
    {
        int size = this->end - this->first;

        T *temp = new T[2*size];

        memcpy(temp,this->first,size*sizeof (T));
        delete []first;
        first = temp;
        last = first+size;
        end = first+2*size;
    }

    //返回指定位置的元素
     T &at(int index)
     {
         int len  = last - first;
         if(index<0||index>len)
         {
             cout<<"超出了"<<endl;
         }
         return first[index];
     }

    //判空
    bool empty()
    {
        return this->last == this->first;
    }

    //判满
    bool full()
    {
        return this->last==this->end;
    }


    //返回第一个元素
    T &front()
    {
        return first;
    }

    //返回最后一个元素
    T &back()
    {
        return last-1;
    }

    //返回元素数量大小
    T size()
    {
        return end-first;
    }
      //clear()

    //在最后添加一个元素
    void push_back(const T e)
    {
        if(this->full())
        {
            this->expand();
        }
        *last = e;
        last++;
    }

    //移除最后一个元素
    void pop_back()
    {
        if(this->empty())
        {
            return;
        }

        last--;
    }

};

int main()
{
    Myvector<int> m;
    m.push_back(2);
    m.push_back(3);
    m.push_back(4);
    m.push_back(5);
    m.push_back(6);
    for(int i=0;i<=4;i++)
    {

      cout<<m.at(i)<<" ";
    }
    cout<<endl;
    cout<< m.size()<<endl;;
    return 0;
}

结果如下图所示:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值