1. 构建接口
1.1 默认构造
vector():_start(nullptr), _end(nullptr), _endOfStorage(nullptr)
{
}
1.2 拷贝构造
vector(const vector<T>& v):_start(nullptr),_end(nullptr),
_endOfStorage(nullptr)
{
reserve(v.size());
for (auto& ch : v)
{
push_back(ch);
}
}
1.3 迭代器构造
template<class InputIterator>
vector(InputIterator first, InputIterator last)
{
while (first != last)
{
push_back(*first);
first++;
}
}
1.4 赋值拷贝
vector<T>& operator=(vector<T> tmp)
{
swap(tmp);
return *this;
}
1.5 析构函数
~vector()
{
delete[] _start;
_start = _end = _endOfStorage = nullptr;
}
2.迭代器的实现
typedef T* iterator;
typedef const T* const_iterator;
iterator begin() const
{
return _start;
}
iterator end() const
{
return _end;
}
const_iterator cbegin()const
{
return _start;
}
const_iterator cend()const
{
return _end;
}
3. 空间接口的实现
int capacity()const
{
return _endOfStorage - _start;
}
int size() const
{
return _end - _start;
}
void reserve(int n)
{
if (n > capacity())
{
int oldsize = size();
iterator tem = new T[n];
for (int i = 0; i < oldsize; i++)
{
tem[i] = _start[i];
}
delete[]_start;
_start = tem;
_end = _start + oldsize;
_endOfStorage = _start + n;
}
}
void resize(size_t n,const T &val=T())
{
if (n > size())
{
reserve(n);
int oldsize = n - size();
for (int i = 0; i <oldsize; i++)
{
push_back(val);
}
}
else
{
_end = _start + n;
}
}
4. []的重载
T& operator[](size_t pos)
{
assert(pos < size());
return _start[pos];
}
const T& operator[](size_t pos)const
{
assert(pos < size());
return _start[pos];
}
5.插入删除接口
void push_back(const T& val)
{
if (_endOfStorage == _end)
{
reserve(capacity() == 0 ? 4 : 2 * capacity());
}
*_end = val;
_end++;
}
void pop_back()
{
_end--;
}
void swap(vector<T>& v)
{
std::swap(_start, v._start);
std::swap(_end, v._end);
std::swap(_endOfStorage, v._endOfStorage);
}
iterator insert(iterator pos, const T& x)
{
if (_end == _endOfStorage)
{
int len = pos - _start;
reserve(capacity() == 0 ? 4 : 2 * capacity());
pos = _start + len;
}
iterator end = _end;
while (end > pos)
{
*end = *(end - 1);
end--;
}
*pos = x;
_end++;
return pos;
}
iterator erase(iterator pos)
{
iterator begin = pos + 1;
while (begin < _end)
{
*(begin - 1) = *begin;
begin++;
}
_end--;
return pos;
}
```