C++ vector 数组实现

现在的年轻人,一言不合就上代码

template <typename T>
class Vector
{
    public:
        explicit Vector(int initSize = 0): theSize(initSize), theCapacity(initSize + SPARE_CAPACITY){};

        Vector(const Vector & rhs) : t(nullptr)
        {
            operator=(rhs);
        }

        virtual ~Vector()
        {
            delete [] t;
        }

        int Size() const
        {
            return theSize;
        }
        void Clear()
        {
            delete [] t;
            for(int i = 0; i < theSize; i++)
                t[i] = nullptr;
        }
        bool isEmpty()
        {
            return theCapacity == theSize;
        }
        void Push_back( T & t)
        {
            if(theSize == theCapacity)
                ReServe(theCapacity * 2 + 1);
            t[theSize++] = t;
        }
        void Pop_back()
        {
            theSize--;
        }
        T & Back() const
        {
            return t[theSize -1];
        }
        T & Front() const
        {
            return t[0];
        }
        const Vector & operator= (const Vector & rhs)
        {
            delete [] t;
            theSize = rhs.Size();
            theCapacity = rhs.theCapacity;

            t = new T[capacity()];
            for(int i = 0; i < Size() ; i++)
                t[i] = rhs[i];
        }
        int capacity() const
        {
            return theCapacity;
        }
        void Reverse()
        {
            int head = 0, tail = theSize - 1;
            T* temp = nullptr;
            while(tail > head)
            {
                temp = t[head];
                t[head] = t[tail];
                t[tail] = t[head];
                tail--;
                head++;
            }
        }
        void ReServe (int newCapacity)
        {
            if(newCapacity < theSize)
                return;
            T * oldArray = t;
            t = new T[newCapacity];
            for(int i = 0; i < theSize; i++)
                t[i] = oldArray[i];
            theCapacity = newCapacity;
            delete [] oldArray;
        }
        void Resize(int newSize)
        {
            if( newSize > theSize)
                ReServe( newSize * 2 + 1);
            theSize = newSize;
        }
        T &operator[] (int index)
        {
            return t[index];
        }
        //自定义iterator类
        iterator Begin()
        {
            return &t[o];
        }
        iterator End()
        {
            return &t[theSize - 1];
        }

        enum { SPARE_CAPACITY = 16};
    private:
        T * t;
        int theSize;
        int theCapacity;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值