成员变量
//迭代器 //对应begin() iterator start; //对应end(), 指向可用空间下一个位置 iterator finish; //指向整个容量的一下个位置 iterator end_of_storage;
push_back,
将新元素插入vector尾端时,先检查是有还有备用空间,如果有就直接在备用空间上构造元素,并调整迭代器finish。
如果没有备用空间,就要扩充空间(重新配置,移动数据,释放原空间)
void push_back(const T& x) { if(finish != end_of_storage) { construct(finish, x); ++finish; } else insert_aux(end(), x); }
insert_aux,单个元素插入指定位置
template<typename T, typename Alloc> void MVector<T, Alloc>::insert_aux(iterator position, const T& x) { // 空间足够 if (finish != end_of_storage) { construct(finish, *(finish - 1)); ++finish; T x_copy = x; // copy_backward(position, finish - 2, finish - 1); *position = x_copy; } else { // 空间不足,重新分配空间 const size_type old_size = size(); const size_type len = old_size != 0 ? 2 * old_size : 1; iterator new_start = data_allocator::allocate(len); iterator new_finish = new_start; try { // 前段拷贝 new_finish = uninitialized_copy(start, position, new_start); // 构造插入的元素 construct(new_finish, x); ++new_finish; // 后段拷贝 uninitialized_copy(position, finish, new_finish); } catch (...) { // 回滚 destroy(new_start, new_finish); data_allocator::deallocate(new_start, len); throw; } // 释放老内存 destroy(begin(), end()); deallocate(); start = new_start; finish = new_finish; end_of_storage = new_start + len; } }