加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

【菜鸟】vector c++实现

发布时间:2020-12-15 07:51:16 所属栏目:Java 来源:网络整理
导读:vector类模板的实现如下: class Vector { public : /*构造函数*/ explicit Vector( int initSize= 0 ) { theSize = 0 ; // theSize是元素索引最大值,最开始一个元素都没有 theCapacity =initSize+ SPARE_CAPABILITY; objects = new Object[theCapacity]; }

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读