C++: day7

1.简单实现部分vector

#include 

using namespace std;

template 
class My_vector
{
private:
    T * first;      //指向第一个元素
    T * last;       //指向最后一个元素
    T * end;        //指向容器末尾

public:
    //构造函数
    My_vector()
    {
        first = last = end = nullptr;
    }
    My_vector(int size = 8)     //默认初始大小为8
    {
        first = new T[size];    //堆区申请空间
        last = first;           //初始为空
        end = first + size;     //容器末尾指针
    }

    //析构函数
    ~My_vector()
    {
        delete []first;                     //释放堆区空间
        first = last = end = nullptr;       //指针指向空
    }

    //拷贝构造
    My_vector(const My_vector &other)
    {
        int size = other.end - other.first;                     //原始容器大小
        this->first = new T[size];                              //创建新容器
        this->end = this->first + size;                         //定位新end指针
        this->last = this->first + (other.last - other.first);  //定位新last指针
    }

    //拷贝赋值
    My_vector &operator=(const My_vector &other)
    {
        delete []this->first;                                   //删除原始空间
        int size = other.end - other.first;                     //原始容器大小
        this->first = new T[size];                              //创建新容器
        this->end = this->first + size;                         //定位新end指针
        this->last = this->first + (other.last - other.first);  //定位新last指针

        return *this;
    }

    //按位查找
    T at(int n)
    {
        return this->first[n];
    }

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

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

    //获取第一个元素
    T &front()
    {
        return *first;
    }

    //获取最后一个元素
    T &back()
    {
        return *(last-1);
    }

    //获取数据长度
    int size()
    {
        return last-first;
    }

    //清空元素,容量不变
    void clear()
    {
        last = first;
    }

    //二倍扩容
    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;
    }

    //实现尾插
        void push_back( const T val)
        {
            if(this->full())
            {
                this->expand();        //满了进行扩容
            }

            *last = val;
            last++;
        }

        //实现尾删
        void pop_back()
        {
            if(this->empty())
            {
                return;
            }

            --last;
        }
};

int main()
{
    My_vector v1(12);              //调用无参构造,数据元素类型为int类型


    //判断当前数组是否为空
    if(v1.empty())
    {
        cout<<"v1 is empty"<C++: day7_第1张图片

 C++: day7_第2张图片

C++: day7_第3张图片

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