现在的年轻人,一言不合就上代码
template <typename T>
class Vector
{
public:
explicit Vector(int initSize = 0): theSize(initSize), theCapacity(initSize + SPARE_CAPACITY){};
Vector(const Vector & rhs) : t(nullptr)
{
operator=(rhs);
}
virtual ~Vector()
{
delete [] t;
}
int Size() const
{
return theSize;
}
void Clear()
{
delete [] t;
for(int i = 0; i < theSize; i++)
t[i] = nullptr;
}
bool isEmpty()
{
return theCapacity == theSize;
}
void Push_back( T & t)
{
if(theSize == theCapacity)
ReServe(theCapacity * 2 + 1);
t[theSize++] = t;
}
void Pop_back()
{
theSize--;
}
T & Back() const
{
return t[theSize -1];
}
T & Front() const
{
return t[0];
}
const Vector & operator= (const Vector & rhs)
{
delete [] t;
theSize = rhs.Size();
theCapacity = rhs.theCapacity;
t = new T[capacity()];
for(int i = 0; i < Size() ; i++)
t[i] = rhs[i];
}
int capacity() const
{
return theCapacity;
}
void Reverse()
{
int head = 0, tail = theSize - 1;
T* temp = nullptr;
while(tail > head)
{
temp = t[head];
t[head] = t[tail];
t[tail] = t[head];
tail--;
head++;
}
}
void ReServe (int newCapacity)
{
if(newCapacity < theSize)
return;
T * oldArray = t;
t = new T[newCapacity];
for(int i = 0; i < theSize; i++)
t[i] = oldArray[i];
theCapacity = newCapacity;
delete [] oldArray;
}
void Resize(int newSize)
{
if( newSize > theSize)
ReServe( newSize * 2 + 1);
theSize = newSize;
}
T &operator[] (int index)
{
return t[index];
}
iterator Begin()
{
return &t[o];
}
iterator End()
{
return &t[theSize - 1];
}
enum { SPARE_CAPACITY = 16};
private:
T * t;
int theSize;
int theCapacity;
};