kujiway

导航

【菜鸟】vector c++实现

vector类模板的实现如下:

class Vector
{
    public:
/*构造函数*/
explicit Vector(int initSize=0) { theSize=0; //theSize是元素索引最大值,最开始一个元素都没有 theCapacity=initSize+SPARE_CAPABILITY; objects=new Object[theCapacity]; } Vector(const Vector &rhs) {        theSize=rhs.theSize;
       theCapacity
=rhs.theCapacity;
       objects
=NULL;//在加入前一定要清理空间
       objects=new Object [theCapacity]; //再申请新空间 for(int i=0;i<rhs.theSize;i++) { objects[i]=rhs.objects[i]; } }

/*重载赋值运算符*/ Vector
& operator=(const Vector &rhs){ if(this!=rhs)//避免自身进行拷贝操作! { delete []objects;//清除原来的空间 theSize=rhs.theSize; theCapacity=rhs.theCapacity; objects=new Object [theCapacity]; for(int i=0;i<theSize;i++) { objects[i]=rhs.objects[i]; } } return *this; }
     
     /*析构函数*/
~Vector(){ //theSize=0; //theCapacity=0; delete []objects; }
/*改变vector的大小*/
void resize(int newSize) { if(newSize<=theCapacity) { theSize=newSize; } else { reserve(newSize*2); theSize=newSize; } }
     /*改变vector的容量
void reserve(int newCapability)//important! { if(newCapability<theSize) return; Object *temp=objects;//将原有内容拷贝到临时数组 delete []objects; objects = new Object[newCapability]; //重新分配空间 for(int i=0;i<theSize;i++) { objects[i]=temp[i]; } theCapacity =newCapability; delete []temp;//清理临时数组 }
Object
&operator[](int index) { return objects[index]; } bool empty() const { if(theSize==0) return true; }
int size() const { return theSize; }
int capacity() const { return theCapacity; }
/*尾端增添新元素*/
void push_back(const Object &x) { if(theSize>=theCapacity) //容量不够,调用thecapacity函数 { reserve(2*theCapacity+1); } objects[theSize]=x; theSize++; }

     /*尾端删除元素*/
void pop_back() { if(theSize!=0) { theSize--; } } const Object &back()const { return objects[theSize-1]; }
     /*支持iterator*/ typedef Object
*iterator; iterator begin() { return objects[0]; }
iterator end() {
return objects[theSize];//end是一个“越界”的迭代器 } static const int SPARE_CAPABILITY=20;

private: int theSize; int theCapacity; Object *objects; };

 

posted on 2019-09-06 13:11  kujiway  阅读(572)  评论(1)    收藏  举报