C++简易版vector(动态机制实现)

#include<iostream>
#include<vector>
using namespace std;
template<typename _Ty>
class Vector {
public:
    Vector(const int& size = 0)
        :   length(size)
        ,   capacity(size)
    {
        data = new int[capacity];       //根据size分配空间
    }
 
    void push_back(const int& value) {
        if (length == capacity)     //当尺寸等于容量时,说明容器已满
            remalloc(capacity+(capacity >> 1));    //此时重新分配1.5倍于原容量大小的空间
        data[length++] = value;
    }
    void remalloc(const int& size) {
        _Ty* new_data = new _Ty[size]();        //创建新空间
        for (int i = 0; i < length && i < size; i++)   
            new_data[i] = data[i];              //将旧空间的值转存到新空间中
        delete data;        //析构旧空间
        data = new_data;    //将指针指向新空间
        capacity = size;    //修改容量
    }
    _Ty& operator[](const int& index) {
        return data[index];  //[]的实现
    }

    _Ty* data;              //数据指针
    int capacity;           //实际容量(即分配的空间)
    int length;             //数组的尺寸
};
int main() {
    Vector<int> vc(5);
    cout << "容量" << vc.capacity << endl;
    vc.push_back(1);
    for (int i = 0; i < vc.length; i++) 
        cout << vc[i] << " ";
    cout << endl;
    cout <<"容量"<< vc.capacity << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40946921/article/details/105142080
今日推荐