#pragma once
#include<iostream>
using namespace std;
#include<assert.h>
#include<string>
#include<stdio.h>
namespace bit
{
template<class T>
class Vector
{
public:
typedef T* Iterator;
Iterator Begin()
{
return _start;
}
Iterator End()
{
return _finish;
}
Vector()
:_start(NULL)
,_finish(NULL)
,_endofstorage(NULL)
{}
Vector(size_t n, const T& value = T())
:_start(NULL)
,_finish(NULL)
,_endofstorage(NULL)
{
Reserve(n);
while(n--)
{
PushBack(value);
//Insert(_finish, value);
}
}
Vector(Iterator first, Iterator last)
{
Reserve(last - first);
while( first != last)
{
PushBack(*first);
++first;
}
}
Vector(const Vector<T>& v)
{
T* tmp = new T[v.Size()];
for(size_t i=0; i<v.Size(); i++)
{
tmp[i] = v[i];
}
_start = tmp;
_finish = _start + v.Size();
_endofstorage = _start + v.Capacity();
}
void Swap(Vector<T>& v)
{
swap(_start, v._start);
swap(_finish, v._finish);
swap(_endofstorage, v._endofstorage);
}
Vector<T>& operator=(Vector<T>& v)
{
if(this != &v)
{
this->Swap(v);
}
return *this;
}
~Vector()
{
delete[] _start;
_start = _finish = _endofstorage = NULL;
}
size_t Size()const
{
return _finish - _start;
}
size_t Capacity()const
{
return _endofstorage - _start;
}
T& operator[](size_t pos)
{
assert(pos < Size());
return _start[pos];
}
const T& operator[](size_t pos)const
{
assert(pos < Size());
return _start[pos];
}
void PushBack(const T& x)
{
Insert(_finish, x);
}
void PopBack()
{
Erase(_finish-1);
}
void Resize(size_t n, const T& value = T())//T()会调用构造函数
{
if(n <= Size())
{
_finish = _start + n;
return ;
}
else
{
Reserve(n);
Iterator it = _finish;
_finish = _start + n;
while(it != _finish)
{
*it = value;
++it;
}
}
}
void Reserve(const size_t n)
{
size_t size = Size();
if(n > Capacity())
{
T* tmp = new T[n];
for(size_t i=0; i<Size(); i++)
{
tmp[i] = _start[i];
}
delete[] _start;
_start = tmp;
_finish = _start + size;
_endofstorage = _start + n;
}
}
Iterator Insert(Iterator pos, const T& x)
{
size_t len = pos - _start;
assert(pos <= _finish);
if(_finish == _endofstorage)
{
size_t newcapacity = Capacity() == 0 ? 2 : Capacity()*2;
Reserve(newcapacity);
pos = _start + len;//重置pos
}
Iterator end = _finish-1;
while(end >= pos)
{
*(end+1) = *(end);
--end;
}
*pos = x;
++_finish;
return pos;
}
Iterator Erase(Iterator pos)
{
assert(pos < _finish);
Iterator cur = pos + 1;
while(cur != _finish)
{
*(cur-1) = *(cur);
++cur;
}
--_finish;
return pos;
}
private:
Iterator _start;
Iterator _finish;
Iterator _endofstorage;
};
}
c++:STL-vector的模拟实现
最新推荐文章于 2024-04-25 18:07:50 发布