C++中vector實現及使用詳解

    vector是)C++中的一種數據結構,確切的說是一個類.它相當於一個動態的數組,當程序員無法知道自己需要的數組的規模多大時,用其來解決問題可以達到最大節約空間的目的

1、vectot與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()來刪除數據,
當刪除數據時,應該知道要刪除尾部的數據,或者是刪除所有數據,還是個別的數據。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章