#include <iostream>
#include <string>
using namespace std;
template <typename T>
class Vector
{
public:
typedef T* Iterator;
typedef const T* constIterator;
public:
Vector()//构造函数
:_start(0)
, _finsh(0)
, _endofStorage(0)
{}
// 向Vector中存入size个元素
Vector(const T* array, size_t size)
:_start(new T[size])
,_endofStorage(_start+size)
,_finsh(_start)
{
for (size_t i = 0; i<size; i++)
{
_start[i] = array[i];
}
_finsh = _start + size;//更新_finsh
}
~Vector()
{
if (_start != NULL)
{
delete[] _start;
_start = NULL;
_finsh = NULL;
_endofStorage = NULL;
}
}
Iterator Begin()
{
return _start;
}
constIterator Begin()const
{
return _start;
}
Iterator End()
{
return _finsh;
}
constIterator End()const
{
return _finsh;
}
size_t Size()const
{
return _finsh - _start;
}
size_t Capacity()const
{
return _finsh - _start;
}
bool Empty()const
{
if (_start != _finsh)
{
return false;
}
return ture;
}
T& operator[](size_t idx)
{
return _start[idx];
}
T& operator[](size_t index)const
{
return _start[idx];
}
// 获取Vector中的第一个元素
T& Front()
{
return *_start;
}
const T& Front()const
{
return *_start;
}
// 获取Vector中的最后一个元素
T& Back()
{
return *_finsh;
}
const T& Back()const
{
return *_finsh;
}
void PushBack(const T& x)
{
CheckCapacity();
*_finsh = x;
_finsh++;
}
void PopBack()
{
_finsh--;
}
// 在pos位置上插入元素x
Iterator Insert(Iterator pos, const T& x)
{
CheckCapacity();
Iterator it = _finsh;
while (it>pos)
{
*it = *(it - 1);
--it;
}
*pos = x;
++_finsh;
}
// 删除pos位置上面的元素
Iterator Erase(Iterator pos)
{
if (_start == NULL)
{
assert(false);
return;
}
Iterator cur = pos;
while (cur < _finsh)
{
*cur = *(cur + 1);
++cur;
}
--_finsh;
}
private:
/*start和finsh之间的元素就是容器有效的元素,而strat和end_of_storage之间的空间就是总容量。*/
T* _start;//容器开头
T* _finsh;//有效元素
T*_endofStorage;//容量
void Swap(Vector<T>& v)
{
std::swap(_start, v._start);
std::swap(_finsh, v._finsh);
std::swap(_endofStorage, v._endofStorage);
}
void CheckCapacity()//检查容量
{
if (_finsh == _endofStorage)
{
// 申请新空间
size_t capacity = 2*(_endofStorage - _start) + 5;//容量满和容量空
T* temp = new T[capacity];
// 拷贝元素
T* pos = _start;
size_t idx = 0;
while (pos < _endofStorage)
temp[idx++] = *pos++;
// 释放旧空间
delete[] _start;
// 指向新空间
_start = temp;
_finsh = _start + idx;
_endofStorage = _start + capacity;
}
}
};
模拟实现vector
最新推荐文章于 2024-10-02 17:51:18 发布