STL顺序容器vector相比数组,可以动态扩容,具体见下图
在STL中vector是一种模板库,部分实现如下:
template<typename T> class MyVector:public Container<T>
{
public:
MyVector();
~MyVector();
void re_capacity(size_t s); //重新扩容
void push(const T& v);
void pop();
const T& begin();
const T& end();
size_t size();
const T& operator[] (size_t i); //下标访问操作符
private:
size_t _size ; //容器内数据大小
size_t _cap ; //已分配容量大小
T* buf ; //首地址,用于创建内存
};
template <typename T> MyVector<T>::MyVector()
{
_size = 0;
_cap = _step;
buf = 0;
re_capacity(_cap);
}
template<typename T> MyVector<T>::~MyVector()
{
free(buf);
}
template<typename T> void MyVector<T>::re_capacity(size_t s)
{
if (!buf)
buf = (T*)malloc(sizeof(T)*s);
else
buf = (T*)realloc(buf, sizeof(T)*s);
}
template<typename T> void MyVector<T>::push(const T& v)
{
if (_size >= _cap)
re_capacity(_cap += _step);
buf[_size++] = v;
}
template<typename T> void MyVector<T>::pop()
{
if (_size)
_size--;
}
template<typename T> const T& MyVector<T>::begin()
{
return buf[0];
}
template<typename T> const T& MyVector<T>::end()
{
if (_size)
return buf[_size - 1];
}
template<typename T> size_t MyVector<T>::size()
{
return _size;
}
template<typename T> const T& MyVector<T>::operator[] (size_t i)
{
if (i >= 0 && i < _size)
return buf[i];
}