上一节博客讲述了vector常见接口的使用,今天主要是对vector这些接口进行模拟实现,下面是相关代码:
#include<iostream>
#include<string>
#include<assert.h>
using namespace std;
namespace TY
{
template<class T>
class Vector
{
public:
typedef T* iterator;
typedef const T* citerator;
iterator Begin()
{
return _start;
}
iterator End()
{
return _finish;
}
citerator cBegin() const
{
return _start;
}
citerator cEnd() const
{
return _finish;
}
size_t Size() const
{
return _finish - _start;
}
size_t Capacity() const
{
return _endofstorage - _start;
}
//构造函数
Vector()
:_start(nullptr)
, _finish(nullptr)
, _endofstorage(nullptr)
{}
//拷贝构造函数
Vector(const Vector<T>& v)
{
_start = new T[v.Capacity()];
iterator it = Begin();
citerator vit = v.cBegin();
while (vit != v.cEnd())
{
*it++ = *vit++;
}
_finish = _start + v.Size();
_endofstorage = _start + v.Capacity();
}
Vector(int n, const T& value = T())
:_start(nullptr)
, _finish(nullptr)
, _endofstorage(nullptr)
{
Reserve(n);
while (n--)
{
PushBack(value);
}
}
//赋值重载hansh
Vector<T>& operator=(const Vector<T>& v)
{
this->Swap(v);
return *this;
}
//析构函数
~Vector()
{
delete[] _start;
_start = _finish = _endofstorage = nullptr;
}
template<class Inputiterator>
Vector(Inputiterator first, Inputiterator last)
{
Reserve(last - first);
while (first != last)
{
PushBack(*first);
++first;
}
}
void Swap(Vector<T>& v)
{
swap(_start, v._start);
swap(_finish, v._finish);
swap(_endofstorage, v._endofstorage);
}
void Reserve(size_t n)
{
if (n > Capacity())
{
//增容
size_t size = Size();
T*tmp = new T[n];
if (_start)
{
for (size_t i = 0; i < size; ++i)
{
tmp[i] = _start[i];//把原空间中的数据拷贝到新开的空间中
}
}
delete[] _start;
_start = tmp;
_finish = _start + size;
_endofstorage = _start + n;
}
}
void Resize(size_t n,const T& value = T())
{
//如果n小于当前的Size(),则数据个数缩小到n
if (n <= Size())
{
_finish = _start + n;
return;
}
//如果n大于容量,增容
if (n > Capacity())
{
Reserve(n);
}
//将Size()扩大到n
iterator it = _finish;
iterator _finish = _start + n;
while (it != _finish)
{
*it = value;
++it;
}
}
void PushBack(const T& x)
{
Insert(End(), x);
}
void PopBack()
{
iterator it = End();
--it;
Erase(it);
}
T& operator[](size_t pos)
{
return _start[pos];
}
iterator Insert(iterator pos, const T& x)
{
assert(pos <= _finish);
//如果空间不够要增容
if (_finish == _endofstorage)
{
size_t posindex = pos - _start;
size_t size = Size();
//如果是第一次插入数据,就要先把容量定为1,后面在有数据的情况下扩容就二倍增加
size_t newCapacity = Capacity() == 0 ? 1 : Capacity() * 2;
Reserve(newCapacity);
pos = _start + posindex;
}
iterator end = _finish - 1;
while (end >= pos)
{
*(end + 1) = *end;
--end;
}
*pos = x;
++_finish;
return pos;
}
iterator Erase(iterator pos)
{
iterator begin = pos + 1;
while (begin != _finish)
{
*(begin - 1) = *begin;
++begin;
}
--_finish;
return pos;
}
private:
iterator _start;//数据存放的开始位置
iterator _finish;//数据存放结束位置的下一个位置
iterator _endofstorage;//容量的最后一个位置
};
}