vector的实现【C++】

平时都是直接使用C++标准库中的容器,今天就参照《数据结构与算法分析》一书简单的实现了下vector向量容器,本程序中没有添加异常以及错误的处理。后期会继续完善。

#include<iostream>
#include<List>

using namespace std;

template<typename Object>
class Vector
{
public:
    explicit Vector(int initSize = 0)
        :theSize(initSize),theCapactity(initSize+SPARE_CAPACITY)
    {objects = new Object[theCapactity];}

    Vector(const Vector& rhs):objects(NULL)
    {operator=(rhs);}

    ~Vector()
    {delete [] objects;}

    const Vector& operator=(const Vector& rhs)
    {
        if(this!=rhs)
        {
            delete [] objects;
            theSize = rhs.size();
            theCapactity = rhs.theCapactity();

            objects = new Object[capacity()];
            for(int k = 0;k < size();k++)
                objects[k] = rhs.objects[k];
        }
        return *this;
    }

    void resize(int newSize)
    {
        if(newSize < theSize)
            reserve(newSize*2+1);
        theSize = newSize;
    }

    void reserve(int newCapacity)
    {
        if(newCapacity < theSize)
            return;
        Object* oldArray = objects;

        objects = new Object[newCapacity];
        for(int k = 0;k<theSize;k++)
            objects[k] = oldArray[k];

        theCapactity = newCapacity;

        delete [] oldArray;
    }

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

    void push_back(const Object & x)
    {
        if(theSize == theCapactity)
            reserve(2*theCapactity + 1);
        objects[theSize++] = x;
    }

    void pop_back()
    {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()];}

    const_iterator end() const
    {return &objects[size()];}

    enum {SPARE_CAPACITY = 16};
private:
    int theSize;
    int theCapactity;
    Object * objects;
};

int main(int argc,char** argv)
{
    //list<int> A;
    //system("pasue");
    Vector<Vector<int>>  CC;
    Vector<int> BB;

    Vector<int> A;
    int a = 1;
    A.push_back(a);
    A.push_back(2);
    A.push_back(3);
    cout<<"A's size is"<<A.size()<<endl;
    for(int i =0 ;i < A.size();i++)
        cout<<"A:"<<A[i]<<endl;

    A.pop_back();
    for(int i =0 ;i < A.size();i++)
        cout<<"A' is:"<<A[i]<<endl; 

    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/att0206/article/details/78267659