zoukankan      html  css  js  c++  java
  • 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 的全部迭代器就失效了。


    演示样例:

    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:



  • 相关阅读:
    利用单片机构成高精度PWM式12位D/A
    【转】FORMAT在DELPHI中的用法
    可定时温湿控制器
    用C#获取硬盘序列号,CPU序列号,网卡MAC地址
    Oracle笔记:查询表相关
    Oracle笔记:视图
    Oracle笔记:维护数据的完整性
    Oracle笔记:索引
    Oracle笔记:pl/sql例外处理
    Oracle笔记:逻辑备份与恢复
  • 原文地址:https://www.cnblogs.com/yutingliuyl/p/7248334.html
Copyright © 2011-2022 走看看