简单实现vector

来源:互联网 发布:周立功单片机培训 编辑:程序博客网 时间:2024/06/05 16:25
#include<iostream>using namespace std;class my_vector{    private://三个指针分别指向第一元素,最后一个元素和空间的最后         int *start;        int *end;        int *end_of_storage;    public:        my_vector():start(0),end(0),end_of_storage(0){}//默认构造         my_vector(int length, const int x)//第一种构造接受大小,和一个值。         {            start=new int[2*length];            end = start + length;            end_of_storage = end + length;              for(int * p = start;p!=end+1;p++)            {                *p = x;            }        }        my_vector(my_vector &p)//拷贝构造         {            start=new int[p.capacity()];            end = start + p.capacity();            end_of_storage = end + p.capacity();                for(int * q = start;q!=end+1;q++)            {                int * n = p.getstart();                *q = p.getnumber(n);                n++;            }        }           int getnumber(int * p )        {            return *p;         }        int *getstart()        {            return start;        }        int *getend()        {            return end;        }        int get_size()        {            return end-start;         }         int capacity()        {            return end_of_storage-start;        }        bool empty()        {            if(getstart() == getend() )                return true;            else                return false;        }        int& operator [](const int &n);//重载下标运算符         ~my_vector()        {            delete []start;        }        void push_back(const int & x)        {            if(end!= end_of_storage)            {                *(++end) = x;            }            else            {                int *n_start,*n_end;                n_start = new   int[ capacity()*2 ];                end_of_storage = n_start + capacity()*2;                int * np = n_start;                for(int * p = start;p!=end+1;p++)                {                    *np = *p;                    np++;                }                delete []start;                start = n_start;            }        }};int& my_vector::operator [](const int &n){            int *p=start;            for(int i=0;i<n;i++)            {                p++;            }            return *p;  }

自己开始学C++时自己实现的一个简单vector。
虽然有很多不足,但现在看来建立思路大体还是对的。

0 0
原创粉丝点击