Vector.h
#include <iostream>
using namespace std;
template<class T>
class Vector
{
public:
typedef T ValueType;
typedef ValueType* lterator;
typedef const ValueType* Constlterator;
typedef ValueType& Reference;
typedef const ValueType& ConstReference;
typedef int SizeType;
Vector()
{
_start = (lterator)new T [3];
_finish = _start;
_endOfStorage = _finish + 3;
}
Vector(int n,const T&value = T())
{
_start = (lterator )new T[3];
_finish = _start;
_endOfStorage = _start+n;;
lterator temp = _start;
while (n)
{
*_finish++ = value;
n--;
}
}
Vector(const Vector<T>& v)
{
_start = (lterator)new T [v.Capacity()];
_finish = _start ;
_endOfStorage = _start + v.Capacity();
for(int n = 0;n<v.Size();n++)
{
*_finish = *(v._start+n);
++_finish;
}
}
~Vector()
{
delete[] _start;
}
lterator Begin()
{
return _start;
}
lterator End()
{
return _finish-1;
}
Constlterator End()const
{
return _finish-1;
}
SizeType Size()const
{
return (_finish-_start);
}
SizeType Capacity()const
{
return (_endOfStorage-_start);
}
bool Empty()const
{
if( _finish-_start)
return false;
else
return true;
}
Reference operator[](int index)
{
if (index<=Capacity())
return *(_start + index);
return *End();
}
ConstReference operator[](size_t index)const
{
if (index<=Capacity())
return *(_start + index);
return *End();
}
Reference Front()
{
return *_start;
}
ConstReference Front()const
{
return *_start;
}
Reference Back()
{
return *_finish;
}
ConstReference Back()const
{
return *_finish;
}
void PushBack(const T&value)
{
if(_finish >=_endOfStorage)
{
int x = Capacity()*2+3;
lterator temp = (lterator)new T[x];
if (temp)
{
int n = Size();
for(int i=0;i<n;i++)
{
temp[i] = _start[i];
}
_start = temp;
_finish = _start+n;
_endOfStorage = _start+x;
}
}
*_finish++ = value;
}
void PopBack()
{
if (!Empty())
{
--_finish;
}
}
lterator Insert(lterator pos,const T&value)
{
int n = _finish - pos;
int x = Capacity()*2+3;
if (_finish >= _endOfStorage)
{
lterator temp = (lterator)new T[x];
if (temp)
{
int i;
for( i=0;i<Size();i++)
{
temp[i] = _start[i];
}
_start = temp;
_finish = _start+i;
_endOfStorage = _start+x;
}
}
pos = _finish - n;
for ( ;n>0;n--)
{
pos[n+1] = pos[n];
}
*pos = value;
++_finish;
return _start;
}
lterator Erase(lterator pos)
{
for (int n=0;n<_finish-pos;n++)
{
pos[n] = pos[n+1];
}
--_finish;
return _start;
}
void ReSize(SizeType newSize,const T&value = T())
{
if (newSize<Size())
{
_finish = _start+newSize;
}
else if (newSize>Size())
{
int n = newSize - Size();
while (n)
{
PushBack(value);
}
}
}
void Clear()const
{
_finish = _start;
}
private:
lterator _start;
lterator _finish;
lterator _endOfStorage;
};
test.c
#include "Vector.h"
#include <iostream>
using namespace std
int main()
{
Vector <int>v1
Vector <int>v3(4,3)
Vector <int >v2(v3)
v3.Insert(&v3.Front(),5)
v3.Erase(v3.End())
v1.PushBack(5)
v1.PushBack(4)
v1.PushBack(3)
v1.PushBack(2)
v1.PushBack(1)
v1[3] = 4
v1.PopBack()
return 0
}