STL源码分析之vector容器

vector与array非常相似,两者唯一差别在于空间运用的灵活性

         array是静态空间,一旦配置了就不能改变;若要改变使用的空间大小,一切琐碎由客户端自己来处理:先配置新空间,然后将元素从旧址一一搬到新址去,在退还原来的空间

         vector则是动态空间,随着元素的加入,它的内部机制会自行扩充空间以容纳新的元素

 

以下为sgi vector源码:

 

//alloc即为之前讲过的空间配置器
template <class T, class Alloc = alloc>
class vector {
public:
  typedef T                     value_type;
  typedef value_type*           pointer;
  typedef const value_type*     const_pointer;
  typedef value_type*           iterator;         //可以看到,这里iterator直接就是指针
  typedef const value_type*     const_iterator;
  typedef value_type&           reference;
  typedef const value_type&     const_reference;
  typedef size_t                size_type;
  typedef ptrdiff_t             difference_type;
 
protected:
    //声明一个空间配置器对象
  typedef simple_alloc<value_type, Alloc> data_allocator;
  iterator start;                               //目前使用空间的开头
  iterator finish;                          //目前使用空间的尾部
  iterator end_of_storage;                      //目前可用空间的尾部
  void insert_aux(iterator position, const T& x);   //此函数将对象x插入到某个位置上,且此函数负责改变vector的大小
 
  void deallocate() {
    //直接将整个vector释放
    if (start) data_allocator::deallocate(start, end_of_storage- start);
  }
 
  void fill_initialize(size_type n, const T& value) {
    start = allocate_and_fill(n, value);
    finish = start + n;
    end_of_storage = finish;
  }
public:
  iterator begin() { return start; }
  iterator end() { return finish; }
  size_type size() const { return size_type(end() -begin()); }
  size_type capacity() const { returnsize_type(end_of_storage - begin()); }
  bool empty() const { return begin() == end(); }
  reference operator[](size_type n) { return *(begin() + n); }
 
//构造函数
  vector() : start(0), finish(0),end_of_storage(0) {}
  vector(size_type n, const T& value) {fill_initialize(n, value); }
  vector(int n, const T& value) {fill_initialize(n, value); }
  vector(long n, const T& value) {fill_initialize(n, value); }
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值