1. 程式人生 > >c++容器擴充套件---verctor的capacity()操作以及擴充套件

c++容器擴充套件---verctor的capacity()操作以及擴充套件

vector<int>c;
c.capacity()返回容器中資料個數,翻倍增長。

1.程式碼

#include <iostream>
  2 #include <vector>
  3 using namespace std;
  4 int main()
  5 {
  6     vector<int>v;
  7     v.push_back(1);
  8     cout<<"capacity == "<<v.capacity()<<endl;
  9 
 10     v.push_back(2);
 11     cout<<"capacity == "<<v.capacity()<<endl;
 12 
 13     v.push_back(3);
 14     cout<<"capacity == "<<v.capacity()<<endl;
 15     return 0;
 16 }

結果:

capacity == 1
capacity == 2
capacity == 4

2.壓縮一個臃腫的vector

很多時候大量的刪除資料,或者通過使用reserver(),結果vector的空間遠遠大於實際的需要。所以需要壓縮vector到它的實際大小。resize()能增加vector的大小。clear()僅僅移除容器內的資料,不能改變capacity()的大小,所以對vector進行壓縮非常重要。

(1)使用capacity()和clear()來操作一個vector

        vector<int>v;
        v.push_back(1);
        cout<<"capacity == "<<v.capacity()<<endl;

        v.push_back(2);
        cout<<"capacity == "<<v.capacity()<<endl;

        v.push_back(3);
        cout<<"capacity == "<<v.capacity()<<endl;

        v.clear();
        cout<<"clear()完之後: "<<v.size()<<endl;
        cout<<"clear()完之後的capacity == "<<v.capacity()<<endl;

結果:

capacity == 1
capacity == 2
capacity == 4
clear()完之後: 0
clear()完之後的capacity == 4

(2)通過上面的結果可以發下如下兩個特點:①capacity()返回容器中資料個數,翻倍增長。②當清除完vector後capacity()仍然是4。

(3)下面定義一個新的vector,將原來的賦值給這個新的vector,看看會出現什麼樣的效果。

        vector<int>v;
        v.push_back(1);
        cout<<"capacity == "<<v.capacity()<<endl;

        v.push_back(2);
        cout<<"capacity == "<<v.capacity()<<endl;

        v.push_back(3);
        cout<<"capacity == "<<v.capacity()<<endl;

        vector<int>v1(v);
        cout<<"新的vector的capacity == "<<v1.capacity()<<endl;

結果:

capacity == 1
capacity == 2
capacity == 4
新的vector的capacity == 3

(3)通過上面的結果發現,新的陣列的容量是元素的個數3。所以可以使用這種方法來達到壓縮vector。接下來可以使用函式swap()進行優化。

        vector<int>v;
        v.push_back(1);
        cout<<"capacity == "<<v.capacity()<<endl;

        v.push_back(2);
        cout<<"capacity == "<<v.capacity()<<endl;

        v.push_back(3);
        cout<<"capacity == "<<v.capacity()<<endl;

        vector<int>v1(v);
        cout<<"新的vector的capacity == "<<v1.capacity()<<endl;

        v.swap(v1);
        cout<<"交換後原來vector的capacity == "<<v.capacity()<<endl;

結果:

capacity == 1
capacity == 2
capacity == 4
新的vector的capacity == 3
交換後原來vector的capacity == 3

(4)再次進行優化。採用匿名物件來代替v1這個中間物件:vector<int> (v).swap(v);

        vector<int>v;
        v.push_back(1);
        cout<<"capacity == "<<v.capacity()<<endl;

        v.push_back(2);
        cout<<"capacity == "<<v.capacity()<<endl;

        v.push_back(3);
        cout<<"capacity == "<<v.capacity()<<endl;


        vector<int> (v).swap(v);
        cout<<"交換後vector的capacity == "<<v.capacity()<<endl;

結果:

capacity == 1
capacity == 2
capacity == 4
交換後vector的capacity == 3

注:C++11中已經提供了shrink_to_fit()函式實現vector的壓縮(你希望呼叫shrink_to_fit來將多餘記憶體還給系統,但標準庫不保證一定可以達到你的目的,類似於inline來實現函式內聯)。