vector实现和使用


1、vector与array

       vector与array非常相似。两者的唯一区别在于空间的运用的灵活性。array是静态空间,一旦配置了就不能改变;vector是动态空间,随着元素的加入,它的内部机制会自行扩充空间以容纳新元素。因此,vector的运用对于内存的合理利用与运用的灵活性有很大的帮助,因此也不必因为害怕空间不足而一开始要求一个大块头的array了。另外,由于vector维护的是一个连续线性空间,所以vector支持随机存取。注意:vector动态增加大小时,并不是在原空间之后持续新空间(因为无法保证原空间之后尚有可供配置的空间),而是以原大小的两倍另外配置一块较大的空间,然后将原内容拷贝过来,然后才开始在原内容之后构造新元素,并释放原空间。因此,对vector的任何操作,一旦引起空间重新配置,指向原vector的所有迭代器就都失效了。这是程序员易犯的一个错误,务需小心。

2、vector原码分析

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

 3、使用vector

(1)文件包含:     

           首先在程序开头处加上#include<vector>以包含所需要的类文件vector同时加上using namespace std;

(2)vector声明:

            使用vector声明数组时,对于一维的数组,格式如右::vector <int> a;(等于声明了一个int数组a[],大小没有指定,可以动态的向里面添加删除);对于多维数组,可以直接给数组名加*,例如用vector代替二维数组.其实只要声明一个一维数组向量即可,而一个数组的名字其实代表的是它的首地址,所以只要声明一个地址的向量即可,即:vector <int *> a.同理想用向量代替三维数组也是一样,vector <int**>a;再往上面依此类推;

(3)成员函数作用

1.push_back   在数组的最后添加一个数据
2.pop_back    去掉数组的最后一个数据 
3.at                得到编号位置的数据
4.begin           得到数组头的指针
5.end             得到数组的最后一个单元+1的指针
6.front            得到数组头的引用
7.back            得到数组的最后一个单元的引用
8.max_size     得到vector最大可以是多大
9.capacity       当前vector分配的大小
10.size           当前使用数据的大小
11.resize         改变当前使用数据的大小,如果它比当前使用的大,者填充默认值
12.reserve      改变当前vecotr所分配空间的大小
13.erase         删除指针指向的数据项
14.clear          清空当前的vector
15.rbegin        将vector反转后的开始指针返回(其实就是原来的end-1)
16.rend          将vector反转构的结束指针返回(其实就是原来的begin-1)
17.empty        判断vector是否为空
18.swap         与另一个vector交换数据

(4)vector的用法实例


vector容器提供了多种创建方法,下面介绍几种常用的。
创建一个Widget类型的空的vector对象:
  vector<Widget> vWidgets;
  
创建一个包含500个Widget类型数据的vector:
  vector<Widget> vWidgets(500);
  
创建一个包含500个Widget类型数据的vector,并且都初始化为0:
  vector<Widget> vWidgets(500, Widget(0));
   
向vector添加一个数据
  vector添加数据的缺省方法是push_back()。
    push_back()函数表示将数据添加到vector的尾部,并按需要来分配内存。


例如:向vector<Widget>中添加10个数据,需要如下编写代码:
  for(int i= 0;i<10; i++) {
    vWidgets.push_back(Widget(i));
  }


获取vector中指定位置的数据
    如果想知道vector是否存放了数据,可以使用empty()。
    获取vector的大小,可以使用size()。


例如,如果想获取一个vector v的大小,但不知道它是否为空,或者是否已经包含了数据,如果为空想设置为-1,
你可以使用下面的代码实现:
  int nSize = v.empty() ? -1 : v.size();
  
访问vector中的数据可以使用 vector::at()
 at()进行了边界检查,如果访问超过了vector的范围,将抛出一个例外。
  
分析下面的代码:
  vector<int> v;
  v.reserve(10);
  
    for(int i=0; i<7; i++) {
    v.push_back(i);
  }
  
    try {

          int iVal1 = v[7];
    // not bounds checked - will not throw
    int iVal2 = v.at(7);
    // bounds checked - will throw if out of range
  } 
    
    catch(const exception& e) {
    cout << e.what();
  }
  
删除vector中的数据
vector能够非常容易地添加数据,也能很方便地取出数据,
同样vector提供了erase(),pop_back(),clear()来删除数据,
当删除数据时,应该知道要删除尾部的数据,或者是删除所有数据,还是个别的数据。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值