STL源码剖析笔记三vector

三、vector容器
      vector的数据安排以及操作方式,与array非常相似。两者的唯一区别在于空间的运用的灵活性。array是静态空间,一旦配置了就不能改变;要换个大(或小)一点的房子,可以,一切琐细都得由客户端自己来:首先配置一块新空间,然后将元素从旧址一一搬往新址,再把原来的空间释还给系统。vector是动态空间,随着元素的加入,它的内部机制会自行扩充空间以容纳新元素。因此,vector的运用对于内存的合理利用与运用的灵活性有很大的帮助,我们再也不必因为害怕空间不足而一开始要求一个大块头的array了,我们可以安心使用array,吃多少用多少。
      vector的实现技术,关键在于其对大小的控制以及重新配置时的数据移动效率。一旦vector的旧有空间满载,如果客户端每新增一个元素,vector的内部只是扩充一个元素的空间,实为不智。因为所谓扩充空间(不论多大),一如稍早所说,是”配置新空间/数据移动/释还旧空间“的大工程,时间成本很高,应该加入某种未雨绸缪的考虑。稍后我们便可看到SGI vector的空间配置策略了。
      另外,由于vector维护的是一个连续线性空间,所以vector支持随机存取
      注意:vector动态增加大小时,并不是在原空间之后持续新空间(因为无法保证原空间之后尚有可供配置的空间),而是以原大小的两倍另外配置一块较大的空间,(这个要看,旧长度的两倍,或者旧长度加新增元素个数)然后将原内容拷贝过来,然后才开始在原内容之后构造新元素,并释放原空间。因此,对vector的任何操作,一旦引起空间重新配置,指向原vector的所有迭代器就都失效了。这是程序员易犯的一个错误,务需小心。
以下是vector定义的源代码摘录:
[cpp]  view plain  copy
  1. #include<iostream>  
  2. using namespace std;  
  3. #include<memory.h>    
  4.   
  5. // alloc是SGI STL的空间配置器  
  6. template <class T, class Alloc = alloc>  
  7. class vector  
  8. {  
  9. public:  
  10.     // vector的嵌套类型定义,typedefs用于提供iterator_traits<I>支持  
  11.     typedef T value_type;  
  12.     typedef value_type* pointer;  
  13.     typedef value_type* iterator;  
  14.     typedef value_type& reference;  
  15.     typedef size_t size_type;  
  16.     typedef ptrdiff_t difference_type;  
  17. protected:  
  18.     // 这个提供STL标准的allocator接口  
  19.     typedef simple_alloc <value_type, Alloc> data_allocator;  
  20.   
  21.     iterator start;               // 表示目前使用空间的头  
  22.     iterator finish;              // 表示目前使用空间的尾  
  23.     iterator end_of_storage;      // 表示实际分配内存空间的尾  
  24.   
  25.     void insert_aux(iterator position, const T& x);  
  26.   
  27.     // 释放分配的内存空间  
  28.     void deallocate()  
  29.     {  
  30.         // 由于使用的是data_allocator进行内存空间的分配,  
  31.         // 所以需要同样使用data_allocator::deallocate()进行释放  
  32.         // 如果直接释放, 对于data_allocator内部使用内存池的版本  
  33.         // 就会发生错误  
  34.         if (start)  
  35.             data_allocator::deallocate(start, end_of_storage - start);  
  36.     }  
  37.   
  38.     void fill_initialize(size_type n, const T& value)  
  39.     {  
  40.         start = allocate_and_fill(n, value);  
  41.         finish = start + n;                         // 设置当前使用内存空间的结束点  
  42.         // 构造阶段, 此实作不多分配内存,  
  43.         // 所以要设置内存空间结束点和, 已经使用的内存空间结束点相同  
  44.         end_of_storage = finish;  
  45.     }  
  46.   
  47. public:  
  48.     // 获取几种迭代器  
  49.     iterator begin() { return start; }  
  50.     iterator end() { return finish; }  
  51.   
  52.     // 返回当前对象个数  
  53.     size_type size() const { return size_type(end() - begin()); }  
  54.     size_type max_size() const { return size_type(-1) / sizeof(T); }  
  55.     // 返回重新分配内存前最多能存储的对象个数  
  56.     size_type capacity() const { return size_type(end_of_storage - begin()); }  
  57.     bool empty() const { return begin() == end(); }  
  58.     reference operator[](size_type n) { return *(begin() + n); }  
  59.   
  60.     // 本实作中默认构造出的vector不分配内存空间  
  61.     vector() : start(0), finish(0), end_of_storage(0) {}  
  62.   
  63.   
  64.     vector(size_type n, const T& value) { fill_initialize(n, value); }  
  65.     vector(int n, const T& value) { fill_initialize(n, value); }  
  66.     vector(long n, const T& value) { fill_initialize(n, value); }  
  67.   
  68.     // 需要对象提供默认构造函数  
  69.     explicit vector(size_type n) { fill_initialize(n, T()); }  
  70.   
  71.     vector(const vector<T, Alloc>& x)  
  72.     {  
  73.         start = allocate_and_copy(x.end() - x.begin(), x.begin(), x.end());  
  74.         finish = start + (x.end() - x.begin());  
  75.         end_of_storage = finish;  
  76.     }  
  77.   
  78.     ~vector()  
  79.     {  
  80.         // 析构对象  
  81.         destroy(start, finish);  
  82.         // 释放内存  
  83.         deallocate();  
  84.     }  
  85.   
  86.     vector<T, Alloc>& operator=(const vector<T, Alloc>& x);  
  87.   
  88.     // 提供访问函数  
  89.     reference front() { return *begin(); }  
  90.     reference back() { return *(end() - 1); }  
  91.   
  92.       
  93.     // 向容器尾追加一个元素, 可能导致内存重新分配  
  94.       
  95.     //                          push_back(const T& x)  
  96.     //                                   |  
  97.     //                                   |---------------- 容量已满?  
  98.     //                                   |  
  99.     //               ----------------------------  
  100.     //           No  |                          |  Yes  
  101.     //               |                          |  
  102.     //               ↓                          ↓  
  103.     //      construct(finish, x);       insert_aux(end(), x);  
  104.     //      ++finish;                           |  
  105.     //                                          |------ 内存不足, 重新分配  
  106.     //                                          |       大小为原来的2倍  
  107.     //      new_finish = data_allocator::allocate(len);       <stl_alloc.h>  
  108.     //      uninitialized_copy(start, position, new_start);   <stl_uninitialized.h>  
  109.     //      construct(new_finish, x);                         <stl_construct.h>  
  110.     //      ++new_finish;  
  111.     //      uninitialized_copy(position, finish, new_finish); <stl_uninitialized.h>  
  112.       
  113.   
  114.     void push_back(const T& x)  
  115.     {  
  116.         // 内存满足条件则直接追加元素, 否则需要重新分配内存空间  
  117.         if (finish != end_of_storage)  
  118.         {  
  119.             construct(finish, x);  
  120.             ++finish;  
  121.         }  
  122.         else  
  123.             insert_aux(end(), x);  
  124.     }  
  125.   
  126.   
  127.       
  128.     // 在指定位置插入元素  
  129.       
  130.     //                   insert(iterator position, const T& x)  
  131.     //                                   |  
  132.     //                                   |------------ 容量是否足够 && 是否是end()?  
  133.     //                                   |  
  134.     //               -------------------------------------------  
  135.     //            No |                                         | Yes  
  136.     //               |                                         |  
  137.     //               ↓                                         ↓  
  138.     //    insert_aux(position, x);                  construct(finish, x);  
  139.     //               |                              ++finish;  
  140.     //               |-------- 容量是否够用?  
  141.     //               |  
  142.     //        --------------------------------------------------  
  143.     //    Yes |                                                | No  
  144.     //        |                                                |  
  145.     //        ↓                                                |  
  146.     // construct(finish, *(finish - 1));                       |  
  147.     // ++finish;                                               |  
  148.     // T x_copy = x;                                           |  
  149.     // copy_backward(position, finish - 2, finish - 1);        |  
  150.     // *position = x_copy;                                     |  
  151.     //                                                         ↓  
  152.     // data_allocator::allocate(len);                       <stl_alloc.h>  
  153.     // uninitialized_copy(start, position, new_start);      <stl_uninitialized.h>  
  154.     // construct(new_finish, x);                            <stl_construct.h>  
  155.     // ++new_finish;  
  156.     // uninitialized_copy(position, finish, new_finish);    <stl_uninitialized.h>  
  157.     // destroy(begin(), end());                             <stl_construct.h>  
  158.     // deallocate();  
  159.       
  160.   
  161.     iterator insert(iterator position, const T& x)  
  162.     {  
  163.         size_type n = position - begin();  
  164.         if (finish != end_of_storage && position == end())  
  165.         {  
  166.             construct(finish, x);  
  167.             ++finish;  
  168.         }  
  169.         else  
  170.             insert_aux(position, x);  
  171.         return begin() + n;  
  172.     }  
  173.   
  174.     iterator insert(iterator position) { return insert(position, T()); }  
  175.   
  176.     void pop_back()  
  177.     {  
  178.         --finish;  
  179.         destroy(finish);  
  180.     }  
  181.   
  182.     iterator erase(iterator position)  
  183.     {  
  184.         if (position + 1 != end())  
  185.             copy(position + 1, finish, position);  
  186.         --finish;  
  187.         destroy(finish);  
  188.         return position;  
  189.     }  
  190.   
  191.   
  192.     iterator erase(iterator first, iterator last)  
  193.     {  
  194.         iterator i = copy(last, finish, first);  
  195.         // 析构掉需要析构的元素  
  196.         destroy(i, finish);  
  197.         finish = finish - (last - first);  
  198.         return first;  
  199.     }  
  200.   
  201.     // 调整size, 但是并不会重新分配内存空间  
  202.     void resize(size_type new_size, const T& x)  
  203.     {  
  204.         if (new_size < size())  
  205.             erase(begin() + new_size, end());  
  206.         else  
  207.             insert(end(), new_size - size(), x);  
  208.     }  
  209.     void resize(size_type new_size) { resize(new_size, T()); }  
  210.   
  211.     void clear() { erase(begin(), end()); }  
  212.   
  213. protected:  
  214.     // 分配空间, 并且复制对象到分配的空间处  
  215.     iterator allocate_and_fill(size_type n, const T& x)  
  216.     {  
  217.         iterator result = data_allocator::allocate(n);  
  218.         uninitialized_fill_n(result, n, x);  
  219.         return result;  
  220.     }  
  221.   
  222.     // 提供插入操作  
  223.       
  224.     //                 insert_aux(iterator position, const T& x)  
  225.     //                                   |  
  226.     //                                   |---------------- 容量是否足够?  
  227.     //                                   ↓  
  228.     //              -----------------------------------------  
  229.     //        Yes   |                                       | No  
  230.     //              |                                       |  
  231.     //              ↓                                       |  
  232.     // 从opsition开始, 整体向后移动一个位置                     |  
  233.     // construct(finish, *(finish - 1));                    |  
  234.     // ++finish;                                            |  
  235.     // T x_copy = x;                                        |  
  236.     // copy_backward(position, finish - 2, finish - 1);     |  
  237.     // *position = x_copy;                                  |  
  238.     //                                                      ↓  
  239.     //                            data_allocator::allocate(len);  
  240.     //                            uninitialized_copy(start, position, new_start);  
  241.     //                            construct(new_finish, x);  
  242.     //                            ++new_finish;  
  243.     //                            uninitialized_copy(position, finish, new_finish);  
  244.     //                            destroy(begin(), end());  
  245.     //                            deallocate();  
  246.       
  247.   
  248.     template <class T, class Alloc>  
  249.     void insert_aux(iterator position, const T& x)  
  250.     {  
  251.         if (finish != end_of_storage)    // 还有备用空间  
  252.         {  
  253.             // 在备用空间起始处构造一个元素,并以vector最后一个元素值为其初值  
  254.             construct(finish, *(finish - 1));  
  255.             ++finish;  
  256.             T x_copy = x;  
  257.             copy_backward(position, finish - 2, finish - 1);  
  258.             *position = x_copy;  
  259.         }  
  260.         else   // 已无备用空间  
  261.         {  
  262.             const size_type old_size = size();  
  263.             const size_type len = old_size != 0 ? 2 * old_size : 1;  
  264.             // 以上配置元素:如果大小为0,则配置1(个元素大小)  
  265.             // 如果大小不为0,则配置原来大小的两倍  
  266.             // 前半段用来放置原数据,后半段准备用来放置新数据  
  267.   
  268.             iterator new_start = data_allocator::allocate(len);  // 实际配置  
  269.             iterator new_finish = new_start;  
  270.             // 将内存重新配置  
  271.             try  
  272.             {  
  273.                 // 将原vector的安插点以前的内容拷贝到新vector  
  274.                 new_finish = uninitialized_copy(start, position, new_start);  
  275.                 // 为新元素设定初值 x  
  276.                 construct(new_finish, x);  
  277.                 // 调整水位  
  278.                 ++new_finish;  
  279.                 // 将安插点以后的原内容也拷贝过来  
  280.                 new_finish = uninitialized_copy(position, finish, new_finish);  
  281.             }  
  282.             catch(...)  
  283.             {  
  284.                 // 回滚操作  
  285.                 destroy(new_start, new_finish);  
  286.                 data_allocator::deallocate(new_start, len);  
  287.                 throw;  
  288.             }  
  289.             // 析构并释放原vector  
  290.             destroy(begin(), end());  
  291.             deallocate();  
  292.   
  293.             // 调整迭代器,指向新vector  
  294.             start = new_start;  
  295.             finish = new_finish;  
  296.             end_of_storage = new_start + len;  
  297.         }  
  298.     }  
  299.   
  300.       
  301.     // 在指定位置插入n个元素  
  302.       
  303.     //             insert(iterator position, size_type n, const T& x)  
  304.     //                                   |  
  305.     //                                   |---------------- 插入元素个数是否为0?  
  306.     //                                   ↓  
  307.     //              -----------------------------------------  
  308.     //        No    |                                       | Yes  
  309.     //              |                                       |  
  310.     //              |                                       ↓  
  311.     //              |                                    return;  
  312.     //              |----------- 内存是否足够?  
  313.     //              |  
  314.     //      -------------------------------------------------  
  315.     //  Yes |                                               | No  
  316.     //      |                                               |  
  317.     //      |------ (finish - position) > n?                |  
  318.     //      |       分别调整指针                              |  
  319.     //      ↓                                               |  
  320.     //    ----------------------------                      |  
  321.     // No |                          | Yes                  |  
  322.     //    |                          |                      |  
  323.     //    ↓                          ↓                      |  
  324.     // 插入操作, 调整指针           插入操作, 调整指针           |  
  325.     //                                                      ↓  
  326.     //            data_allocator::allocate(len);  
  327.     //            new_finish = uninitialized_copy(start, position, new_start);  
  328.     //            new_finish = uninitialized_fill_n(new_finish, n, x);  
  329.     //            new_finish = uninitialized_copy(position, finish, new_finish);  
  330.     //            destroy(start, finish);  
  331.     //            deallocate();  
  332.       
  333.   
  334.     template <class T, class Alloc>  
  335.     void insert(iterator position, size_type n, const T& x)  
  336.     {  
  337.         // 如果n为0则不进行任何操作  
  338.         if (n != 0)  
  339.         {  
  340.             if (size_type(end_of_storage - finish) >= n)  
  341.             {      // 剩下的备用空间大于等于“新增元素的个数”  
  342.                 T x_copy = x;  
  343.                 // 以下计算插入点之后的现有元素个数  
  344.                 const size_type elems_after = finish - position;  
  345.                 iterator old_finish = finish;  
  346.                 if (elems_after > n)  
  347.                 {  
  348.                     // 插入点之后的现有元素个数 大于 新增元素个数  
  349.                     uninitialized_copy(finish - n, finish, finish);  
  350.                     finish += n;    // 将vector 尾端标记后移  
  351.                     copy_backward(position, old_finish - n, old_finish);  
  352.                     fill(position, position + n, x_copy); // 从插入点开始填入新值  
  353.                 }  
  354.                 else  
  355.                 {  
  356.                     // 插入点之后的现有元素个数 小于等于 新增元素个数  
  357.                     uninitialized_fill_n(finish, n - elems_after, x_copy);  
  358.                     finish += n - elems_after;  
  359.                     uninitialized_copy(position, old_finish, finish);  
  360.                     finish += elems_after;  
  361.                     fill(position, old_finish, x_copy);  
  362.                 }  
  363.             }  
  364.             else  
  365.             {   // 剩下的备用空间小于“新增元素个数”(那就必须配置额外的内存)  
  366.                 // 首先决定新长度:就长度的两倍 , 或旧长度+新增元素个数  
  367.                 const size_type old_size = size();  
  368.                 const size_type len = old_size + max(old_size, n);  
  369.                 // 以下配置新的vector空间  
  370.                 iterator new_start = data_allocator::allocate(len);  
  371.                 iterator new_finish = new_start;  
  372.                 __STL_TRY  
  373.                 {  
  374.                     // 以下首先将旧的vector的插入点之前的元素复制到新空间  
  375.                     new_finish = uninitialized_copy(start, position, new_start);  
  376.                     // 以下再将新增元素(初值皆为n)填入新空间  
  377.                     new_finish = uninitialized_fill_n(new_finish, n, x);  
  378.                     // 以下再将旧vector的插入点之后的元素复制到新空间  
  379.                     new_finish = uninitialized_copy(position, finish, new_finish);  
  380.                 }  
  381. #         ifdef  __STL_USE_EXCEPTIONS  
  382.                 catch(...)  
  383.                 {  
  384.                     destroy(new_start, new_finish);  
  385.                     data_allocator::deallocate(new_start, len);  
  386.                     throw;  
  387.                 }  
  388. #         endif /* __STL_USE_EXCEPTIONS */  
  389.                 destroy(start, finish);  
  390.                 deallocate();  
  391.                 start = new_start;  
  392.                 finish = new_finish;  
  393.                 end_of_storage = new_start + len;  
  394.             }  
  395.         }  
  396.     }  
  397. };  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值