【C++】Day7 标准莫板库

1. 实现vector相关函数

#include 

using namespace std;


template 
class Myvector
{
private:
    T* first;
    T* last;
    T* end;
public:
    Myvector(int size =10){      //构造函数
        this->first = new T[size];
        this->last = this->first;
        this->end = this->first+size;
    }

    ~Myvector() {   //析构函数
        delete []first;
        this->first=nullptr;
        this->last=nullptr;
        this->end=nullptr;
    }

    Myvector(const Myvector& other)     //拷贝构造
    {
        int size = other.end - other.first;
        this->first = new T[size];
        int len = other.last - other.frist;
        memcpy(this->_frist, other._first,sizeof(T)*len);
        this->_last = this->_frist + len;
        this->_end = this->_frist + size;
    }

    //容器是否为空?
    bool empty()
    {
        return this->last == this->first;
    }

    //容器是否为满?
    bool full()
    {
        return this->last == this->end;
    }

    T &front()
    {
        return *this->first;
    }

    T &back()
    {
        return  *(this->last-1);
    }

    void clear()
    {
        this->last = this->first;
    }

    //有效元素个数
    int size()
    {
        return this->last - this->first;
    }
    void expand()   //二倍扩容
    {
        int size = this->last - this->first;
        T* temp = new T[2*size];
        memcpy(temp,this->first,sizeof(T)*(end-first));
        delete []first;
        this->first = temp;
        this->last=this->first+size;
        this->end=this->first+2*size;
    }

    void push_back(const T& e)  //尾加
    {
        if(full())
        {
            this->expand();
        }
        *last++ = e;
    }

    void pop_back() //尾删
    {
        if(empty()) return;
        last--;
    }

    T &at(int index)
    {
        if(index < 0 || index>=this->size())
        {
            cout<<"下标越界"<first[index];
    }
};


int main()
{
    Myvector v1;

    //判断当前数组是否为空
    if(v1.empty())  cout<<"v1 is empty"<v1 is empty
v1.size = 0
20 21 22 23 24 25 26 27 28 29
v1.front = 0
v1.back = 999
0 21 22 23 24 25 26 27 999
v1.size = 0

2. 思维导图

【C++】Day7 标准莫板库_第1张图片

 

你可能感兴趣的:(c++,开发语言)