如何在容器里盛满60升纯酒精已满的情况下reallocate memory

vector所用存储开始是未构造内存,还没有存储任何对象。将元素复制或增加到这个预分配空间时,必须使用allocator类的construct成员构造元素。
以下以代码实现这个过程。
//pseduo-implementation of memory allocation strategy for vector container
template &&class T& class vector {
& & & & & &vector( ): M_start(0), M_finish(0), M_end_of_storage(0) {}
& & & & & &void push_back(const T&);
& & & & & &// ...
& & & & & &static std::allocator&T& &//object to get raw memory
& & & & & &void reallocate(); & & & & & & &//get more space and copy existing element
& & & & & &T* M_ & & & & & & & & & & & &//pointer to first element in the array
& & & & & &T* M_ & & & & & & & & & & &//pointer to last element in the array
& & & & & &T* M_end_of_ & & //pointer to end of the space of vector
& & & & & &//....
可以使用这些指针来确定vector的大小和容量:
vector的size(实际使用)等于M_finish - M_
vector的capacity(在必须重新分配vector之前,可以定义的元素的综述)等于M_end_of_storage - M_start
自由空间(在需要重新分配之前,可以增加的元素的数目)是
M_end_of_storage - M_start
push_back成员使用这些指针将新元素添加到末尾
template &class T&
void vector&T&::push_back(const T& t)
& & & & //are we out of space?
& & & & if(M_finish == M_end_of_storage)
& & & & & & &reallocate(); &//gets more space and copies and existing elements
& & & & alloc.construct(M_finish, t);
& & & & ++M_
重新分配元素与复制元素
template &&class T& void vector&T&::reallocate()&
& & & &//compute size of current array and allocate space for twice as many elements
& & & &std::ptrdiff_t size = M_finish - M_
& & & &std::ptrdiff_t newcapacity = 2 * max(size,1);
& & & &//allocate space to hold newcapacity number of element of type T
& & & T* newelements = alloc.allocate(newcapacity);
& & & &//construct copies of the existing elements in the new space
& & & &uninitialized_copy(M_start, M_finish, newelements);
& & & &//destory the old elemetn in reverse order
& & & &for(T *p = M_ p != M_ /*empty*/)
& & & & & & & & alloc.destory(--p);
& & & & //deallocate cannot be called on a 0 pointer
& & & & &if(M_start)
& & & & & & alloc.deallocate(M_start, M_end_of_storage-M_start)
& & & & &//make our data structure point to the new elements
& & & & & & M_start =
& & & & & & &M_finish = M_start +
& & & & & & M_end_of_storage = M_start +
你可能喜欢的
人生就像一场没有目的地的旅行,过往只是沿途的一站This site in other countries/regions:用C实现vect容器_百度文库
两大类热门资源免费畅读
续费一年阅读会员,立省24元!
文档贡献者
评价文档:
喜欢此文档的还喜欢
用C实现vect容器
把文档贴到Blog、BBS或个人站等:
普通尺寸(450*500pix)
较大尺寸(630*500pix)
大小:8.05KB
登录百度文库,专享文档复制特权,财富值每天免费拿!
你可能喜欢
20080份文档

我要回帖

更多关于 装满水的密闭容器 的文章

 

随机推荐