# 2. Vector 定义

## 2.1. Vector嵌套型别定义

typedef T           value_type;         // 泛型定义
typedef value_type* pointer;            // 原生指针
typedef value_type* iterator;           // 迭代器
typedef value_type& reference;          // 原生引用
typedef size_t      size_type;          // 容器unsigned类型
typedef ptrdiff_t   different_type;     // 容器signed类型

## 2.2. Vector 成员变量

iterator start;             // 表示目前使用空间的头
iterator finish;            // 表示目前使用空间的尾
iterator end_of_storage;    // 表示目前可用空间的尾

## 2.3. Vector 构造函数

vector() : start(0),finish(0),end_of_storage(0) {}
vector(size_type n, const T& value)
{
start  = allocate_and_fill(n, value); //申请一段连续内存地址，并填充n个value值
finish = start + n;
end_of_storage = finish;
}
vector(int n, const T& value)
{
start  = allocate_and_fill(n, value);
finish = start + n;
end_of_storage = finish;
}
vector(long n, const T& value)
{
start  = allocate_and_fill(n, value);
finish = start + n;
end_of_storage = finish;
}
explicit vector(size_type n)
{
start  = allocate_and_fill(n, T()); //explicit关键字的作用就是防止类构造函数的隐式自动转换.
finish = start + n;
end_of_storage = finish;
}

## 2.4. Vector 常用函数

iterator begin()
{
return start;
}
iterator end()
{
return finish;
}
iterator size()
{
return size_type(end()-begin());
}
size_type capacity()
{
return size_type(end_of_storage - begin());
}
bool empty()
{
return begin() == end();
}
reference operator[](size_type n)
{
return *(begin()+n);
}
reference front()
{
return *begin();
}
reference back()
{
return *(end()-1);
}
reference push_back(const T& x)
{
if (finish != end_of_storage) { // 如果内存足够
construct(finish,x); //在finish所指之处产生x的复制品
++finish;
} else {
insert_aux(end(),x); //在end()后新增x
}
}
void push_back()
{
--finish;
destory(finish); //摧毁finish
}
iterator erase(iterator position)
{
if (position+1 != end())
copy(position+1,finish,position); //后续元素往前移动
--finish;
destroy(finish);
return position;
}
void resize(size_type new_size, const T& x)
{
if (new_size < size())
erase(begin()+new_size,end());
else
insert(end(),new_size-size(),x);
}
void resize(size_type new_size)
{
resize(new_size,T());
}
void clear()
{
erase(begin(),end());
}