比较懒,把方法的实现都写在类里面了
template <class Type>
class Vector1
{
public:
Vector1(): element(0), first_free(0), end(0)
{
}
~Vector1()
{
alloc.deallocate(element, end-element);
}
void push_back(const Type& t)
{
if(first_free==end)
{
reallocate();
}
alloc.construct(first_free, t);
first_free++;
}
Type operator[](int index)
{
return *(element+index);
}
Type* begin()
{
return element;
}
Type* End()
{
return first_free;
}
class Iterator
{
public:
Iterator(): currentPos(0){};
Iterator& operator=(Type* t)
{
currentPos=t;
return *this;
}
~Iterator(){};
Iterator& operator++()
{
++currentPos;
return *this;
}
Type& operator*()
{
return *currentPos;
}
Iterator operator++(int)
{
Iterator ret(*this);
++(*this);
return ret;
}
bool operator==(Type* pt)
{
return currentPos==pt;
}
bool operator!=(Type* pt)
{
return currentPos!=pt;
}
private:
Type* currentPos;
};
private:
allocator<Type> alloc;
void reallocate()
{
std::ptrdiff_t size=first_free-element;
std::ptrdiff_t newcapacity=2*max(size, 1);
Type* newelements=alloc.allocate(newcapacity);
uninitialized_copy(element, first_free, newelements);
for(Type* p=first_free; p!=element;)
{
alloc.destroy(--p);
}
if(element)
{
alloc.deallocate(element, end-element);
}
element=newelements;
first_free=element+size;
end=element+newcapacity;
}
Type* element;
Type* first_free;
Type* end;
};