STL源码剖析 容器 stl_vector.h

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie

vector

----------------------------------------------------------------------

描述:

1.迭代器

vector 维护的是一个连续线性空间,它的迭代器是普通指针,

能满足 RandomAccessIterator 所有必要条件:operator*, operator->,operator++,operator--,operator+,

operator-,operator+=,operator-=,operator[]

2.数据结构

vector所采用的数据结构是线性连续空间。

迭代器 start、finish分别表示配置得来的连续空间中目前已经被使用的范围

迭代器 end_of_storage 指向整块连续空间的尾端

增加新元素时,如果走过当时的容量,则容量会扩充至两倍。

如果两倍容量仍不足,就扩张至足够大的容量。

扩充容量的过程为:重新配置、元素移动、释放原空间

所谓动态增加大小,并不是在原空间之后接续新空间,因为无法保证原空间之后

尚有可供配置的空间。因此,对 vector 的任何操作,一旦引起空间重新配置,

指向原 vector 的所有迭代器就失效了。

图4-2

示例:

vector<int> V;
V.insert(V.begin(), 3);
assert(V.size() == 1 && V.capacity() >= 1 && V[0] == 3);

源码:

#ifndef __SGI_STL_INTERNAL_VECTOR_H
#define __SGI_STL_INTERNAL_VECTOR_H

__STL_BEGIN_NAMESPACE 

#if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
#pragma set woff 1174
#endif

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; //vector 的迭代器是个原生的指针
  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;

#ifdef __STL_CLASS_PARTIAL_SPECIALIZATION
  typedef reverse_iterator<const_iterator> const_reverse_iterator;
  typedef reverse_iterator<iterator> reverse_iterator;
#else /* __STL_CLASS_PARTIAL_SPECIALIZATION */
  typedef reverse_iterator<const_iterator, value_type, const_reference,
                           difference_type>  const_reverse_iterator;
  typedef reverse_iterator<iterator, value_type, reference, difference_type>
          reverse_iterator;
#endif /* __STL_CLASS_PARTIAL_SPECIALIZATION */
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);
  void deallocate() {
    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; }
  const_iterator begin() const { return start; }
  iterator end() { return finish; }
  const_iterator end() const { return finish; }
  reverse_iterator rbegin() { return reverse_iterator(end()); }
  const_reverse_iterator rbegin() const {
    return const_reverse_iterator(end());
  }
  reverse_iterator rend() { return reverse_iterator(begin()); }
  const_reverse_iterator rend() const {
    return const_reverse_iterator(begin());
  }
  size_type size() const { return size_type(end() - begin()); }
  size_type max_size() const { return size_type(-1) / sizeof(T); }
  size_type capacity() const { return size_type(end_of_storage - begin()); }
  bool empty() const { return begin() == end(); }
  reference operator[](size_type n) { return *(begin() + n); }
  const_reference operator[](size_type n) const { return *(begin() + n); }

  vector() : start(0), finish(0), end_of_storage(0) {}
  //构造函数,允许指定 vector 大小 n 和初值 value
  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); }
  explicit vector(size_type n) { fill_initialize(n, T()); }

  vector(const vector<T, Alloc>& x) {
    start = allocate_and_copy(x.end() - x.begin(), x.begin(), x.end());
    finish = start + (x.end() - x.begin());
    end_of_storage = finish;
  }
#ifdef __STL_MEMBER_TEMPLATES
  template <class InputIterator>
  vector(InputIterator first, InputIterator last) :
    start(0), finish(0), end_of_storage(0)
  {
    range_initialize(first, last, iterator_category(first));
  }
#else /* __STL_MEMBER_TEMPLATES */
  vector(const_iterator first, const_iterator last) {
    size_type n = 0;
    distance(first, last, n);
    start = allocate_and_copy(n, first, last);
    finish = start + n;
    end_of_storage = finish;
  }
#endif /* __STL_MEMBER_TEMPLATES */
  ~vector() {
    destroy(start, finish);
    deallocate();
  }
  vector<T, Alloc>& operator=(const vector<T, Alloc>& x);
  void reserve(size_type n) {
    if (capacity() < n) {
      const size_type old_size = size();
      iterator tmp = allocate_and_copy(n, start, finish);
      destroy(start, finish);
      deallocate();
      start = tmp;
      finish = tmp + old_size;
      end_of_storage = start + n;
    }
  }
  reference front() { return *begin(); }
  const_reference front() const { return *begin(); }
  reference back() { return *(end() - 1); }
  const_reference back() const { return *(end() - 1); }
  //
  void push_back(const T& x) {
    if (finish != end_of_storage) { //检查是否还有备用空间
      construct(finish, x); //有,直接在备用空间上构造元素
      ++finish; //调整迭代器 finish
    }
    else
      insert_aux(end(), x); //没有,扩充空间(重新配置、元素移动、释放原空间)
  }
  void swap(vector<T, Alloc>& x) {
    __STD::swap(start, x.start);
    __STD::swap(finish, x.finish);
    __STD::swap(end_of_storage, x.end_of_storage);
  }
  iterator insert(iterator position, const T& x) {
    size_type n = position - begin();
    if (finish != end_of_storage && position == end()) {
      construct(finish, x);
      ++finish;
    }
    else
      insert_aux(position, x);
    return begin() + n;
  }
  iterator insert(iterator position) { return insert(position, T()); }
#ifdef __STL_MEMBER_TEMPLATES
  template <class InputIterator>
  void insert(iterator position, InputIterator first, InputIterator last) {
    range_insert(position, first, last, iterator_category(first));
  }
#else /* __STL_MEMBER_TEMPLATES */
  void insert(iterator position,
              const_iterator first, const_iterator last);
#endif /* __STL_MEMBER_TEMPLATES */

  void insert (iterator pos, size_type n, const T& x);
  void insert (iterator pos, int n, const T& x) {
    insert(pos, (size_type) n, x);
  }
  void insert (iterator pos, long n, const T& x) {
    insert(pos, (size_type) n, x);
  }

  void pop_back() {
    --finish; //将尾端标记往前移一格,表示将放弃尾端元素
    destroy(finish); //析构尾端元素
  }
  //清除 position 指向的元素
  iterator erase(iterator position) {
    if (position + 1 != end())
      copy(position + 1, finish, position);
    --finish;
    destroy(finish);
    return position;
  }
  //清除[first, last)中的所有元素
  iterator erase(iterator first, iterator last) {
    iterator i = copy(last, finish, first); 将 [last, finish) 指示的元素拷贝至 first 迭代器开头的地方
    destroy(i, finish); 析构[i, finish) 里的元素
    finish = finish - (last - first); 调整 finish 指示的位置 last - first 表示清除掉了的元素个数
    return first;
  }
  void resize(size_type new_size, const T& x) {
    if (new_size < size())
      erase(begin() + new_size, end());
    else
      insert(end(), new_size - size(), x);
  }
  void resize(size_type new_size) { resize(new_size, T()); }
  //调用 erase 清除所有元素
  void clear() { erase(begin(), end()); }

protected:
  //配置而后填充
  iterator allocate_and_fill(size_type n, const T& x) {
    iterator result = data_allocator::allocate(n); //配置 n 个元素空间
    __STL_TRY {
      uninitialized_fill_n(result, n, x); //全局函数。全根据 result 的类型特性(type traits)决定使用算法 fill_n() 或反复调用  construct() 来完成任务
      return result;
    }
    __STL_UNWIND(data_allocator::deallocate(result, n));
  }

#ifdef __STL_MEMBER_TEMPLATES
  template <class ForwardIterator>
  iterator allocate_and_copy(size_type n,
                             ForwardIterator first, ForwardIterator last) {
    iterator result = data_allocator::allocate(n);
    __STL_TRY {
      uninitialized_copy(first, last, result);
      return result;
    }
    __STL_UNWIND(data_allocator::deallocate(result, n));
  }
#else /* __STL_MEMBER_TEMPLATES */
  iterator allocate_and_copy(size_type n,
                             const_iterator first, const_iterator last) {
    iterator result = data_allocator::allocate(n);
    __STL_TRY {
      uninitialized_copy(first, last, result);
      return result;
    }
    __STL_UNWIND(data_allocator::deallocate(result, n));
  }
#endif /* __STL_MEMBER_TEMPLATES */

#ifdef __STL_MEMBER_TEMPLATES
  template <class InputIterator>
  void range_initialize(InputIterator first, InputIterator last,
                        input_iterator_tag) {
    for ( ; first != last; ++first)
      push_back(*first);
  }

  // This function is only called by the constructor.  We have to worry
  //  about resource leaks, but not about maintaining invariants.
  template <class ForwardIterator>
  void range_initialize(ForwardIterator first, ForwardIterator last,
                        forward_iterator_tag) {
    size_type n = 0;
    distance(first, last, n);
    start = allocate_and_copy(n, first, last);
    finish = start + n;
    end_of_storage = finish;
  }

  template <class InputIterator>
  void range_insert(iterator pos,
                    InputIterator first, InputIterator last,
                    input_iterator_tag);

  template <class ForwardIterator>
  void range_insert(iterator pos,
                    ForwardIterator first, ForwardIterator last,
                    forward_iterator_tag);

#endif /* __STL_MEMBER_TEMPLATES */
};

template <class T, class Alloc>
inline bool operator==(const vector<T, Alloc>& x, const vector<T, Alloc>& y) {
  return x.size() == y.size() && equal(x.begin(), x.end(), y.begin());
}

template <class T, class Alloc>
inline bool operator<(const vector<T, Alloc>& x, const vector<T, Alloc>& y) {
  return lexicographical_compare(x.begin(), x.end(), y.begin(), y.end());
}

#ifdef __STL_FUNCTION_TMPL_PARTIAL_ORDER

template <class T, class Alloc>
inline void swap(vector<T, Alloc>& x, vector<T, Alloc>& y) {
  x.swap(y);
}

#endif /* __STL_FUNCTION_TMPL_PARTIAL_ORDER */

template <class T, class Alloc>
vector<T, Alloc>& vector<T, Alloc>::operator=(const vector<T, Alloc>& x) {
  if (&x != this) {
    if (x.size() > capacity()) {
      iterator tmp = allocate_and_copy(x.end() - x.begin(),
                                       x.begin(), x.end());
      destroy(start, finish);
      deallocate();
      start = tmp;
      end_of_storage = start + (x.end() - x.begin());
    }
    else if (size() >= x.size()) {
      iterator i = copy(x.begin(), x.end(), begin());
      destroy(i, finish);
    }
    else {
      copy(x.begin(), x.begin() + size(), start);
      uninitialized_copy(x.begin() + size(), x.end(), finish);
    }
    finish = start + x.size();
  }
  return *this;
}

template <class T, class Alloc>
void vector<T, Alloc>::insert_aux(iterator position, const T& x) {
  if (finish != end_of_storage) { // 不是备用空间不够才会调用 insert_aux 来插入元素吗? 为什么还会出现 finish != end_of_storage 的情况 ?
								  // --> 除了 push_back 不够空间时会调用 insert_aux,正常的 insert 也是调用 insert_aux 实现的。

	//为什么不直接 copy_backward(position, finish - 1, finish), 然后 *position = x_copy 呢?
	construct(finish, *(finish - 1));
    ++finish;
    T x_copy = x;
    copy_backward(position, finish - 2, finish - 1);
    *position = x_copy;
  }
  else { //无备用空间 position == finish
    const size_type old_size = size();
    const size_type len = old_size != 0 ? 2 * old_size : 1;
    //如果原大小为0,则配置1个元素大小的空间,否则配置原大小两倍的空间
	iterator new_start = data_allocator::allocate(len); //实际配置
    iterator new_finish = new_start;
    __STL_TRY {
	  //将原空间的全部内容拷贝到新空间 positition
      new_finish = uninitialized_copy(start, position, new_start);
      //为新元素设定初值 x
	  construct(new_finish, x);
      //调整迭代器 finish
	  ++new_finish;
	  //??我觉得下面这行代码没用。因为无备用空间的情况,position == finish
      new_finish = uninitialized_copy(position, finish, new_finish);
    }

#       ifdef  __STL_USE_EXCEPTIONS
    catch(...) { //异常竟然可以用三个小点 ... ??
	  //回滚
      destroy(new_start, new_finish);
      data_allocator::deallocate(new_start, len);
      throw;
    }
#       endif /* __STL_USE_EXCEPTIONS */

	//析构并释放原空间
    destroy(begin(), end());
    deallocate();
	//调整迭代器,指向新 vector
    start = new_start;
    finish = new_finish;
    end_of_storage = new_start + len;
  }
}

template <class T, class Alloc>
//从 position 开始,插入 n 个元素,元素初值为 x
void vector<T, Alloc>::insert(iterator position, size_type n, const T& x) {
  if (n != 0) { // 当 n != 0 才进行以下所有操作
    if (size_type(end_of_storage - finish) >= n) { //备用空间大于新增元素个数
      T x_copy = x;
      const size_type elems_after = finish - position; //插入点之后的的现有元素个数
      iterator old_finish = finish;
      if (elems_after > n) { //"插入点之后的的现有元素个数"大于"新增元素个数"
        //空间还没初始化时用 uninitialized_copy , 已经初始化了用 copy_backward
		uninitialized_copy(finish - n, finish, finish);
        finish += n;
        copy_backward(position, old_finish - n, old_finish);
        fill(position, position + n, x_copy); //从插入点开始填入新值
      }
      else { //"插入点之后的的现有元素个数"小于"新增元素个数"
        uninitialized_fill_n(finish, n - elems_after, x_copy);
        finish += n - elems_after;
        uninitialized_copy(position, old_finish, finish);
        finish += elems_after;
        fill(position, old_finish, x_copy);
      }
    }
    else {//备用空间小于新增元素个数
      const size_type old_size = size();
	  // 首先决定新长度:旧长度的两倍或旧长度+新元素个数,这两个中取最大值
      const size_type len = old_size + max(old_size, n);
      iterator new_start = data_allocator::allocate(len);
      iterator new_finish = new_start;
      __STL_TRY {
	    //先用 uninitialized_copy 将旧 vector 的插入点之前的元素复制到新空间
        new_finish = uninitialized_copy(start, position, new_start);
        //再用 uninitialized_fill_n 将新增元素填入新空间
		new_finish = uninitialized_fill_n(new_finish, n, x);
        //最后再用 uninitialized_copy 将旧 vector 的插入点之后的元素复制到新空间
		new_finish = uninitialized_copy(position, finish, new_finish);
      }
#         ifdef  __STL_USE_EXCEPTIONS
      catch(...) {
        destroy(new_start, new_finish);
        data_allocator::deallocate(new_start, len);
        throw;
      }
#         endif /* __STL_USE_EXCEPTIONS */
      //清除并释放旧的 vector
	  destroy(start, finish);
      deallocate();
	  //调整标记
      start = new_start;
      finish = new_finish;
      end_of_storage = new_start + len;
    }
  }
}

#ifdef __STL_MEMBER_TEMPLATES

template <class T, class Alloc> template <class InputIterator>
void vector<T, Alloc>::range_insert(iterator pos,
                                    InputIterator first, InputIterator last,
                                    input_iterator_tag) {
  for ( ; first != last; ++first) {
    pos = insert(pos, *first);
    ++pos;
  }
}

template <class T, class Alloc> template <class ForwardIterator>
void vector<T, Alloc>::range_insert(iterator position,
                                    ForwardIterator first,
                                    ForwardIterator last,
                                    forward_iterator_tag) {
  if (first != last) {
    size_type n = 0;
    distance(first, last, n);
    if (size_type(end_of_storage - finish) >= n) {
      const size_type elems_after = finish - position;
      iterator old_finish = finish;
      if (elems_after > n) {
        uninitialized_copy(finish - n, finish, finish);
        finish += n;
        copy_backward(position, old_finish - n, old_finish);
        copy(first, last, position);
      }
      else {
        ForwardIterator mid = first;
        advance(mid, elems_after);
        uninitialized_copy(mid, last, finish);
        finish += n - elems_after;
        uninitialized_copy(position, old_finish, finish);
        finish += elems_after;
        copy(first, mid, position);
      }
    }
    else {
      const size_type old_size = size();
      const size_type len = old_size + max(old_size, n);
      iterator new_start = data_allocator::allocate(len);
      iterator new_finish = new_start;
      __STL_TRY {
        new_finish = uninitialized_copy(start, position, new_start);
        new_finish = uninitialized_copy(first, last, new_finish);
        new_finish = uninitialized_copy(position, finish, new_finish);
      }
#         ifdef __STL_USE_EXCEPTIONS
      catch(...) {
        destroy(new_start, new_finish);
        data_allocator::deallocate(new_start, len);
        throw;
      }
#         endif /* __STL_USE_EXCEPTIONS */
      destroy(start, finish);
      deallocate();
      start = new_start;
      finish = new_finish;
      end_of_storage = new_start + len;
    }
  }
}

#else /* __STL_MEMBER_TEMPLATES */

template <class T, class Alloc>
void vector<T, Alloc>::insert(iterator position,
                              const_iterator first,
                              const_iterator last) {
  if (first != last) {
    size_type n = 0;
    distance(first, last, n);
    if (size_type(end_of_storage - finish) >= n) {
      const size_type elems_after = finish - position;
      iterator old_finish = finish;
      if (elems_after > n) {
        uninitialized_copy(finish - n, finish, finish);
        finish += n;
        copy_backward(position, old_finish - n, old_finish);
        copy(first, last, position);
      }
      else {
        uninitialized_copy(first + elems_after, last, finish);
        finish += n - elems_after;
        uninitialized_copy(position, old_finish, finish);
        finish += elems_after;
        copy(first, first + elems_after, position);
      }
    }
    else {
      const size_type old_size = size();
      const size_type len = old_size + max(old_size, n);
      iterator new_start = data_allocator::allocate(len);
      iterator new_finish = new_start;
      __STL_TRY {
        new_finish = uninitialized_copy(start, position, new_start);
        new_finish = uninitialized_copy(first, last, new_finish);
        new_finish = uninitialized_copy(position, finish, new_finish);
      }
#         ifdef __STL_USE_EXCEPTIONS
      catch(...) {
        destroy(new_start, new_finish);
        data_allocator::deallocate(new_start, len);
        throw;
      }
#         endif /* __STL_USE_EXCEPTIONS */
      destroy(start, finish);
      deallocate();
      start = new_start;
      finish = new_finish;
      end_of_storage = new_start + len;
    }
  }
}

#endif /* __STL_MEMBER_TEMPLATES */

#if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
#pragma reset woff 1174
#endif

__STL_END_NAMESPACE 

#endif /* __SGI_STL_INTERNAL_VECTOR_H */

// Local Variables:
// mode:C++
// End:

STL源码剖析 容器 stl_vector.h,布布扣,bubuko.com

时间: 2024-10-06 10:58:13

STL源码剖析 容器 stl_vector.h的相关文章

STL源码剖析 容器 stl_hashtable.h

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie hashtable --------------------------------------------------------------------------- 二叉搜索树具有对数平均时间的表现,它建立在输入数据有足够的随机性的假设 hashtable 有常数平均时间的表现,基于统计,不需依赖输入元素的随机性 hashtalbe 的简单实现: 所有元素都 16-bits 不带正负

《STL源码剖析》---stl_vector.h阅读笔记

在STL中,最常用的就是容器,最常用的容器就是vector了.vector类似内置数组.但是数组是静态的,一旦配置就不能再变大小,而容器的大小事容器本身自己调整的.在实现容器的代码中可以看到,容器可以动态增大,但是不能动态减小. 容器有已用空间和可用空间,已用空间就是容器已经使用了的空间,可用空间就是指vector的大小capacity. 容器是占用一段连续线性空间,所以容器的迭代器就等价于原生态的指针(这是造成我一直以为迭代器就是指针的原因),vector迭代器类型是RandomAccessI

STL源码剖析 容器 stl_set.h

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie set ------------------------------------------------------------------------ 所有元素都会根据元素的键值自动被排序. 不可以通过 set 的迭代器改变 set 的元素值.因为 set 元素值就是其键值,关系到 set 元素的排列规则. set<T>::iterator 被定义为底层 RB-tree 的 const

STL源码剖析 容器 stl_tree.h

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie RB-tree(红黑树) -------------------------------------------------------------------------- 平衡二叉搜索树 --> 平衡可提高搜索效率 常见的平衡二叉搜索树有: AVL-tree(任何节点的左右子树高度相差最多 1).红黑树.AA-tree AVL-tree 破坏平衡的情况及恢复平衡的方法 恢复时要先找到失

STL源码剖析 容器 stl_map.h

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie map -------------------------------------------------------------------------------- 所有元素都会根据元素的键值自动被排序. map的所有元素都是 pair,同时拥有实值和键值. 不可以修改元素的键值,因为它关系到 map 元素的排列规则 可以修改元素的实值,因为它不影响 map 的排列规则 map ite

STL源码剖析 容器 stl_list.h

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie list ---------------------------------------------------------------------- ??为什么很多在算法库里有的算法还要在类的成员函数里重新实现一遍? -->1.因为算法库里的是通用的,对于具体的类来说效率不高. 比如说 reverse 如果直接用 stl_algo.h 里的 reverse,会再调用 iter_swap,

STL源码剖析 容器 stl_deque.h

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie deque ------------------------------------------------------------------------ ??一直看不懂 operator->() ,不明白它为什么不用接受参数,直接 return &(operator*()) 好像我们用迭代器的时候也不没怎么用到这个函数,甚至我都不会用 1.概述 vector 是单向开口的连续线性空

STL源码剖析 容器 stl_stack.h

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie stack ------------------------------------------------------------- stack 是一种配接器(adapter),以某种容器作为底部结构,改变其接口,使之符合"先进后出"的特性. SGI STL 默认以 deque 为 stack 底部结构 没有遍历行为,没有遍历器 示例: #include <stack&g

STL源码剖析 容器 stl_queue.h

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie queue ---------------------------------------------------------------------- stack 是一种配接器(adapter),以某种容器作为底部结构,改变其接口,使之符合"先进先出"的特性. SGI STL 默认以 deque 为 stack 底部结构 没有遍历行为,没有遍历器 示例: #include &l