以下是上一篇博客实现的带空间适配器alloctor的vector代码!
template<typename T>
struct Allocator
{
//负责内存开辟
T* allocate(size_t size)
{
return (T*)malloc(sizeof(T)*size);
}
//负责内存释放!
void deallocate(void* p)
{
free(p);
}
//负责对象构造!
void construct(T* p,const T&val)
{
new(p) T(val);//定位new,在指定的地址(p)存放val
}
void destroy(T* p)
{
p->~T();//~T()代表T类型析构函数
}
};
//vector
template<typename T,typename Alloc = Allocator<T>>
{
public:
vector(int size=10,const Alloc& alloc = Allocator<T>())
:_allocator(alloc)
{
//_first=new T[size];
_first = _allocator.allocate(size);
_last=_first;
_end=_first+size;
}
//析构容器有效个数的元素,然后释放_first指针指向的堆内存
~vector()
{
//delete[] _first;
for(T* p=_first;p!=_last;++p)
{
//把_first指针指向的数组有效元素进行析构操作
_allocator.destory(p);
}
_allocator.deallocate(_first);
_first = _last = _end = nullptr;
}
vector(const vector<T>& rhs)
{
int size=rhs._end - rhs._first;
//_first=new T[size];
_first = _allocator.allocate(size);
int len = rhs._last - rhs._first;
for(int i=0;i<len;++i)
{
//_first[i] = rhs._first[i];
_allocator.construct(_first+i,rhs._first[i]);
}
_last = _first+len;
_end = _first+size;
}
vector<T>& operator= (const vector<T>& rhs)
{
if(this == &rhs)
return ;
//delete[] _first;
for(T* p=_first;p!=_last;++p)
{
//把_first指针指向的数组有效元素进行析构操作
_allocator.destory(p);
}
_allocator.deallocate(_first);
int size=rhs._end - rhs._first;
//_first=new T[size];
_first = _allocator.allocate(size);
int len = rhs._last - rhs._first;
for(int i=0;i<len;++i)
{
//_first[i] = rhs._first[i];
_allocator.construct(_first+i,rhs._first[i]);
}
_last = _first+len;
_end = _first+size;
return *this;
}
void push_back(T& val)
{
if(full())
expand();
//*_last=val;
//_last++;
_allocator.construct(_last,val);
_last++;
}
void pop_back()
{
if(empty())
return ;
--_last;
_allocator.destroy(_last);
}
//返回容器末尾的值
T back()const
{
return *(_last-1);
}
bool full()const
{
return _last == _end;
}
bool empty()const
{
return _first == _last;
}
int size()const
{
return _last - _first;
}
T& operator[](int index)
{
if(index < 0 || index >=size())
{
throw "OutOfRangeException";
}
return _first[index];
}
//迭代器一般实现成容器的嵌套类型
class iterator
{
public:
iterator(T* ptr=nullptr)
:_ptr(ptr){}
bool operator!=(const iterator& it)const
{
return _ptr!=it._ptr;
}
void operator++()//重载前置++
{
_ptr++;
}
T& operator*()
{
return *_ptr;
}
const T& operator*()const
{
return *_ptr;
}
private:
T* _ptr;
};
//需要给容器提供begin和end方法
iterator begin(){return iterator(_first);}
iterator end(){return iterator(_last);}
private:
T* _first;//指向数组起始位置
T* _last;//指向数组中有效元素的后继位置
T* _end;//指向数组空间的后继位置
Alloc _allocator;//定义容器的空间适配器对象!
void expand()//2倍扩容
{
int size = _end - _first;
//T* ptmp = new T[2*size];
T* ptmp = _allocator.allocate(2*size);
for(int i=0;i<size;i++)
{
//ptmp[i] = _first[i];
_allocator.construct(ptmp+i,_first[i]);
}
//delete[] _first;
for(T* p=_first;p!=_last;++p)
{
_allocator.destroy(p);
}
_allocator.deallocate(_first)
_first = ptmp;
_last = _fist + size;
_end = _first + size*2;
}
}