STL vector源码分析

vector

1.vector概述

vector和array非常类似,区别在于array是静态空间,一旦配置就不能改变了。空间不够之后需要换个更大的空间,这个工作需要有客户端自己打理。vector是动态空间,内部机制会自行扩充空间来容纳新元素。vector技术中关键部分在于,对大小的配置以及重新配置时数据移动的效率。

2.vector定义

template <class _Tp, class _Alloc = __STL_DEFAULT_ALLOCATOR(_Tp) >
class vector : protected _Vector_base<_Tp, _Alloc> 
{
  // requirements:

  __STL_CLASS_REQUIRES(_Tp, _Assignable);

private:
  typedef _Vector_base<_Tp, _Alloc> _Base;
public:
  typedef _Tp value_type;
  typedef value_type* pointer;
  typedef const value_type* const_pointer;
  typedef value_type* 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;
.
.
.}
这里从比<vector>更底层的<stl_vector.h>中摘出来的,其中需要注意的有两个地方:
1. __STL_DEFAULT_ALLOCATOR(_Tp)是SGI STL的空间配置器。
2.上面标红的是vector的迭代器,vector迭代器所需要的操作行为,入operator*、operator->、operator++、operator--、operator+、operator-、operator+=、operator-=,
vector支持随机存取,而普通指针也具备这样的能力,所以,vector<T>的迭代器就是T*,实质上是指针。

template <class _Tp, class _Alloc = __STL_DEFAULT_ALLOCATOR(_Tp) >
class vector : protected _Vector_base<_Tp, _Alloc> 
{
...
protected:
#ifdef __STL_HAS_NAMESPACES
  using _Base::_M_allocate;
  using _Base::_M_deallocate;
  using _Base::_M_start;
  using _Base::_M_finish;
  using _Base::_M_end_of_storage;
#endif /* __STL_HAS_NAMESPACES */
...
}
vector所采用的数据结构为线性连续空间,两个迭代器_M_start,_M_finish分别指向配置得来的连续空间中目前已被使用的范围,并以_M_end_of_storage指向整块连续空间(含备用空间)的尾端。利用这三个迭代器,可以轻松的提供首尾标识,大小,容量,空容器判断,注标([ ])运算子,最前端元素,最后端元素等等机能。

template <class _Tp, class _Alloc = __STL_DEFAULT_ALLOCATOR(_Tp) >
class vector : protected _Vector_base<_Tp, _Alloc> 
{
...
public:
  iterator begin() { return _M_start; }
  const_iterator begin() const { return _M_start; }
  iterator end() { return _M_finish; }
  const_iterator end() const { return _M_finish; }

  reverse_i
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值