1.Vector模板实现
#pragma once
#include<iostream>
#include<assert.h>
using namespace std;
template<class T>
class Vector
{
public:
Vector()
:_start(NULL)
,_finish(NULL)
,_endofstorage(NULL)
{}
Vector(const Vector<T>& v)
{
if(v.Size()>0)
{
_start=new T[v.Size()];
memcpy(_start,v._start,sizeof(T)*v.Size());
_finish=_start+v.Size();
_endofstorage=_start+v.Capacity();
}
else
{
_start=_finish=_endofstorage=NULL;
}
}
Vector<T>& operator=(const Vector<T>& v)
{
size_t size=v.Size();
delete [] _start;
T* tmp=new T[size];
for(size_t i=0; i<size; ++i)
{
tmp[i]=v._start[i];
}
_start=tmp;
_finish=_start+size;
_endofstorage=_start+v.Capacity();
return *this;
}
~Vector()
{
delete[] _start;
_start=_finish=_endofstorage=NULL;
}
void Insert(size_t pos,const T& x)
{
assert(pos<=Size());
if(_finish==_endofstorage)
{
Expand(Capacity()*2);
}
T* end=_finish;
while(end>=_start+pos)
{
*(end+1)=*end;
--end;
}
_start[pos]=x;
++_finish;
}
void Expand(size_t n)
{
if(Empty())
{
_start=new T[3];
_finish=_start;
_endofstorage=_start+3;
}
else if(n>Capacity())
{
size_t size=Size();
T* tmp=new T[n];
//类型萃取
for(size_t i=0; i<size; ++i)
{
tmp[i]=_start[i];//调用string的赋值运算符
}
_start=tmp;
_finish=_start+size;
_endofstorage=_start+n;
}
}
void PushBack(const T& x)
{
Insert(Size(),x);
}
void Erase(size_t pos)
{
assert(pos<Size());
T* cur=_start+pos+1;
while(cur!=_finish)
{
*(cur-1)=*cur;
++cur;
}
--_finish;
}
void PopBack()
{
Erase(Size()-1);
}
void PopFront()
{
Erase(0);
}
bool Empty()
{
return _start==_finish;
}
size_t Capacity()const
{
return _endofstorage-_start;
}
size_t Size()const
{
return _finish-_start;
}
size_t Find(const T& x)
{
size_t size=Size();
for(size_t i=0; i<size; ++i)
{
if(_start[i]=x)
{
return i;
}
}
return -1;
}
void Print()
{
for(size_t i=0; i<Size(); ++i)
{
cout<<_start[i]<<" ";
}
cout<<endl;
}
T& Back()
{
return *(_finish-1);
}
T& Front()
{
return *_start;
}
size_t operator[](size_t index)
{
return _start[index];
}
private:
T* _start;
T* _finish;
T* _endofstorage;
};
void TestVector()
{
Vector<int> v1;
v1.PushBack(1);
v1.PushBack(2);
v1.PushBack(3);
v1.PushBack(4);
Vector<int> v2(v1);
//Vector<int> v2;
//v2=v1;
v1.Print();
v2.Print();
}
#pragma once
#include<iostream>