#include <iostream>
#include <memory>
using std::cout;
using std::endl;
template<typename T>
class Vector
{
public:
typedef T * iterator;
Vector()
: _start(nullptr)
, _finish(nullptr)
, _end_of_storage(nullptr)
{
}
~Vector();
void push_back(const T &value);
void pop_back();
int size() const;
int capacity() const;
iterator begin()
{
return _start;
}
iterator end()
{
return _finish;
}
private:
void reallocate();//重新分配内存,动态扩容要用的
private:
//进行空间申请与释放,以及对象构建与销毁的类
static std::allocator<T> _alloc;
T *_start; //指向数组中的第一个元素
T *_finish; //指向最后一个实际元素之后的那个元素
T *_end_of_storage; //指向数组本身之后的位置
};
template <typename T>
std::allocator<T> Vector<T>::_alloc;
template <typename T>
Vector<T>::~Vector()
{
if(_start)
{
while(_finish != _start)
{
_alloc.destroy(--_finish);//销毁对象
}
_alloc.deallocate(_start, capacity());//空间回收
}
}
template <typename T>
void Vector<T>::push_back(const T &value)
{
//vector是不是满的
if(size() == capacity())
{
reallocate();//进行扩容
}
if(size() < capacity())
{
_alloc.construct(_finish++, value);//插入对象
}
}
template <typename T>
void Vector<T>::pop_back()
{
if(size() > 0)
{
_alloc.destroy(--_finish);
}
}
template <typename T>
int Vector<T>::size() const//记录元素的个数
{
return _finish - _start;
}
template <typename T>
int Vector<T>::capacity() const
{
return _end_of_storage - _start;
}
template <typename T>
void Vector<T>::reallocate()//重新分配内存,动态扩容要用的
{
int oldCapacity = capacity();
int newCapacity = 2 * oldCapacity > 0 ? 2 * oldCapacity: 1;//新空间扩容的大小
T *ptmp = _alloc.allocate(newCapacity);//申请新的空间
if(_start)
{
/* copy(_start, _finish, ptmp); */
std::uninitialized_copy(_start, _finish, ptmp);//在未初始化的空间上拷贝对象
while(_finish != _start)
{
_alloc.destroy(--_finish);//老的空间上的对象一个个进行销毁(考虑边界问题)
/* _alloc.destroy(_start++);//老的空间上的对象一个个进行销毁(考虑边界问题) */
}
_alloc.deallocate(_start, oldCapacity);//老的空间进行了回收
}
//三个指针之前是指向老的空间,然后扩容之后需要将三个指针与
//新的空间产生联系
_start = ptmp;
_finish = _start + oldCapacity;
_end_of_storage = _start + newCapacity;
}
template <typename Container>
void printCapacity(const Container &con)
{
cout << "con.size() = " << con.size() << endl;
cout << "con.capacity() = " << con.capacity() << endl;
}
void test()
{
Vector<int> number;
printCapacity(number);
cout << endl;
number.push_back(1);
printCapacity(number);
cout << endl;
number.push_back(2);
printCapacity(number);
cout << endl;
number.push_back(3);
printCapacity(number);
cout << endl;
number.push_back(4);
printCapacity(number);
cout << endl;
number.push_back(5);
printCapacity(number);
cout << endl;
for(auto &elem : number)
{
cout << elem << " ";
}
cout << endl;
}
int main(int argc, char **argv)
{
test();
return 0;
}