数据结构-Vector实现(C++)

<span style="font-family:Microsoft YaHei;font-size:18px;">#include<iostream>
using namespace std;


template <typename Object>
class Vector{


public:
    //构造函数,初始化数组
    Vector(int initSize = 0):theSize(initSize),theCapacity(initSize+SPARE_CAPACITY){
        objects = new Object[theCapacity];
    }
    //复制构造函数
    Vector(const Vector &rhs):objects(NULL){
        operator=(rhs);
        }
    //释放数组
    ~Vector(){
        delete[] objects;
    }
    //深度复制,=符号重新定义,operator函数,this作为左值
    const Vector& operator=(const Vector &rhs){
            if(this!=&rhs){//不要自己复制给自己了
                int k;
                delete[] objects;//释放掉初始化的那个
                theSize=rhs.size();
                theCapacity=rhs.theCapacity;

                objects = new Object[capacity()];
                for(k=0;k<size();++k){
                    objects[k]=rhs.objects[k];
                }
            }
            return *this;
    }
    void resize(int newSize){//增加当前元素个数
        if(newSize>theCapacity){//大于当前容量了
            reverse(2*newSize+1);//选择容量变为当前的2倍
            theSize= newSize;//更新一下当前数组的大小
        }
    }
    void reverse(int newCapacity){//增大容量
    int k;
     if(newCapacity<theSize)
        return;
     Object* oldArray=objects;
     objects = new Object[newCapacity];
     for(k=0;k<size();++k){
         objects[k] = oldArray[k];
      }
      theCapacity = newCapacity;
      delete[] oldArray;
   }
   Object& operator[](int index){//重载返回数组
        return objects[index];
   }
   const Object& operator[](int index) const{//不变
        return objects[index];
   }
   //顺序装入元素
   void push_back(int k){
       if(theSize==theCapacity){
        reverse(2*theSize+1);
       }
       objects[theSize++]=k;
   }
   void pop_back(){
        --theSize();
   }
   bool empty(){
      return size()==0;
   }
    int capacity() const{
        return theCapacity;
    }
    int size() const {
        return theSize;
    }
    const Object &back() const{
        return objects[theSize-1];
    }
    typedef Object* iterator;
    typedef const Object * const_iterator;


    iterator begin(){
        return &objects[0];
    }
    const_iterator begin() const {
        return &objects[0];
    }
    iterator end(){
        return &objects[size()];
    }
    iterator end()const {
        return &objects[size()];
    }
   enum{SPARE_CAPACITY};
private:
    int theSize;//当前个数
    int theCapacity;//数组大小
    Object *objects;//通过指针变量分配内存块
};
int main()
{
    Vector<int> a;
    Vector<int> b;
    int i=10;
    for(i=0;i<5;++i){
        a.push_back(i);
    }
    for(Vector<int>::iterator iter=a.begin();iter!=a.end();++iter){
        cout<<*iter<<" ";
    }
    return 0;
}</span>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值