目录
//4个默然函数
//vecotr<int> v
vector()
:_start(nullptr)
,_finish(nullptr)
,_endofstorage(nullptr)
{}
template <class InputIterator >
vector(InputIterator first, InputIterator finish)
: _start(nullptr)
, _finish(nullptr)
, _endofstorage(nullptr)
{
while (first != finish)
{
push_back(*first);
first++;
}
}
vector(const vector& v)
{
_start = new T[v.capacity()];
_finish = _start + v.size();
_endofstorage = _start + v.capacity();
int i = 0;
while (i < v.size())
{
(*this)[i] = v[i];
i++;
}
}
vector operator=(vector v) //这里不用引用就是要复用上面的拷贝构造
{
swap(v);
return *this;
}
~vector()
{
delete[] _start;
_start = _finish = _endofstorage = nullptr;
}
//迭代器
typedef T* iterator;
typedef const T* const_iterator;
iterator begin()
{
return _start;
}
iterator end()
{
return _finish;
}
const_iterator begin() const
{
return _start;
}
const_iterator end() const
{
return _finish;
}
//访问
T& operator[](size_t pos)
{
return *(_start + pos);
}
const T& operator[](size_t pos) const
{
return *(_start + pos);
}
void push_back(const T& val)//const 引用用好,是自定义类型的时候提高效率
{
if (_finish == _endofstorage) //需要扩容
{
capacity() == 0 ? reserve(4) : reserve(size() * 2);
}
*_finish = val;
_finish++;
}
iterator insert(iterator pos, const T& val)
{
if (_finish == _endofstorage) //需要扩容
{
if (_finish == nullptr) //第一次插入
{
_start = new T[4];
_finish = _start;
_endofstorage = _start + 4;
*_finish = val;
_finish++;
pos = begin();
}
else //不是第一次插入
{
size_t old = pos - _start;
reserve(capacity() * 2);
pos = _start + old; //不然pos会失效
//挪动
iterator tail = _finish;
while (tail != pos)
{
*tail = *(tail - 1);
tail--;
}
*pos = val;
_finish++;
}
}
else
{
//挪动
iterator tail = _finish;
while (tail != pos)
{
*tail = *(tail - 1);
tail--;
}
*pos = val;
_finish++;
}
return pos;
}
iterator erase(iterator pos)
{
iterator cur = pos;
while (cur != _finish - 1)
{
*cur = *(cur + 1);
cur++;
}
_finish--;
return pos;
}
void resize(size_t n, T val = T())
{
if (n > size())
{
if (n > capacity())
{
reserve(n);
}
size_t a = size();
size_t b = capacity();
int i = 0;
size_t sz = size();
while (i < n - sz)
{
push_back(val);
i++;
}
size_t aa = size();
size_t bb = capacity();
}
else
{
int i = 0;
while (i < size() - n)
{
_finish--;
}
}
}
void reserve(size_t n)
{
if (n > _endofstorage - _start)
{
size_t sz = size();
T* tem = new T[n];
int i = 0;
if (_start)
{
while (i < sz)
{
tem[i] = (*this)[i];
i++;
}
delete[] _start;
}
_start = tem;
_finish = _start + sz;
_endofstorage = _start + n;
}
}
//访问个数
size_t size() const
{
return _finish - _start;
}
size_t capacity() const
{
return _endofstorage - _start;
}
//交换
void swap(vector& v)
{
std::swap(_start, v._start);
std::swap(_finish, v._finish);
std::swap(_endofstorage, v._endofstorage);
}