首页 > 编程语言 > 详细

【菜鸟】vector c++实现

时间:2019-09-06 14:48:15      阅读:75      评论:0      收藏:0      [点我收藏+]

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; };

 

【菜鸟】vector c++实现

原文:https://www.cnblogs.com/jsehunstudy/p/11474268.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!