Vector

来源:互联网 发布:win10自带软件 编辑:程序博客网 时间:2024/06/08 19:12
template<typename Object>class Vector {public:    explicit 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;    }    // =函数    const Vector & operator=(const Vector & rhs){        //首先不能自身=        if(this!=&rhs){            //注意要释放旧数组            delete[] objects;            //注意,时rhs.size            theSize=rhs.size();            theCapacity=rhs.theCapacity;            objects=new Object[capacity()];            //赋值            for(int i=0;i<size();i++){                objects[i]=rhs.objects[i];            }        }        return *this;    }    void resize(int newSize){        //如果大于容量,容量随着增大        if(newSize>theCapacity){            reserve(newSize*2+1);            theSize=newSize;        }    }    //修改容量,搬迁    void reserve(int newCapacity){        if(newCapacity<theSize){            return ;        }        //增大容量后,相当于分配了一个新的内存块.复制旧内存块内容到新的,清空旧的        Object *oldObject=objects;        objects=new Object(newCapacity);        for(int i=0;i<theSize;i++){            objects[i]=oldObject[i];        }        theCapacity=newCapacity;        delete [] oldObject;    }    //修改函数的[]    Object & operator[](int index){        return objects[index];    }    //访问函数的[]    const Object & operator[](int index) const{        return objects[index];    }    bool empty() const{        return size()==0;    }    int size() const{        return theSize;    }    int capacity()const{        return theCapacity;    }    //末尾插入    void push_back(const Object & x){        //先判断容量==大小        if(capacity()==size()){            reserve(2*capacity()+1);        }        objects[theSize++]=x;    }    //删除末尾    void pop_back(){        theSize--;    }    //返回末尾    const Object & back() const{        return objects[size()-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()];    }    const_iterator end() const{        return &objects[size()];    }    enum{SPARE_CAPACITY=16};private:    int theSize;    int theCapacity;    Object *objects;};

依照<<数据结构与算法分析>> C++描述重新打一遍.

0 0
原创粉丝点击