向量大小和容量

向量大小只是向量中元素的數量:

  1. size() 成員函式查詢當前向量大小。如果 size 為 0,方便 empty() 函式返回 true

    vector<int> v = { 1, 2, 3 }; // size is 3
    const vector<int>::size_type size = v.size();
    cout << size << endl; // prints 3
    cout << boolalpha << v.empty() << endl; // prints false
    
  2. 預設構造的向量以 0 開頭:

    vector<int> v; // size is 0
    cout << v.size() << endl; // prints 0
    
  3. N 元素新增到向量會增加 N大小 (例如,通過 push_back()insert()resize() 函式)。

  4. 從向量中刪除 N 元素會減少 N大小 (例如,通過 pop_back()erase()clear() 函式)。

  5. Vector 對其大小有一個特定於實現的上限,但在到達它之前可能會耗盡 RAM:

    vector<int> v;
    const vector<int>::size_type max_size = v.max_size();
    cout << max_size << endl; // prints some large number
    v.resize( max_size ); // probably won't work
    v.push_back( 1 ); // definitely won't work
    

常見錯誤: 尺寸不一定(甚至通常)int

// !!!bad!!!evil!!!
vector<int> v_bad( N, 1 ); // constructs large N size vector
for( int i = 0; i < v_bad.size(); ++i ) { // size is not supposed to be int!
    do_something( v_bad[i] );
}

向量容量大小不同。雖然大小只是向量當前有多少元素,但容量是它分配了多少元素/保留記憶體。這很有用,因為太大的太頻繁(重新)分配可能很昂貴。

  1. capacity() 成員函式查詢當前向量容量容量始終大於或等於大小

    vector<int> v = { 1, 2, 3 }; // size is 3, capacity is >= 3
    const vector<int>::size_type capacity = v.capacity();
    cout << capacity << endl; // prints number >= 3
    
  2. 你可以通過 reserve( N ) 函式手動預留容量(它將向量容量改為 N):

    // !!!bad!!!evil!!!
    vector<int> v_bad;
    for( int i = 0; i < 10000; ++i ) {
        v_bad.push_back( i ); // possibly lot of reallocations
    }
    
    // good
    vector<int> v_good;
    v_good.reserve( 10000 ); // good! only one allocation
    for( int i = 0; i < 10000; ++i ) {
        v_good.push_back( i ); // no allocations needed anymore
    }
    
  3. 你可以請求 shrink_to_fit() 釋放多餘的容量(但實施不必遵守你的要求)。這對於節省使用的記憶體很有用:

    vector<int> v = { 1, 2, 3, 4, 5 }; // size is 5, assume capacity is 6
    v.shrink_to_fit(); // capacity is 5 (or possibly still 6)
    cout << boolalpha << v.capacity() == v.size() << endl; // prints likely true (but possibly false)
    

Vector 會自動部分管理容量,當你新增元素時,它可能會決定增長。實施者喜歡使用 2 或 1.5 作為增長因子(黃金比率將是理想值 - 但由於是有理數而不切實際)。另一方面,向量通常不會自動縮小。例如:

vector<int> v; // capacity is possibly (but not guaranteed) to be 0
v.push_back( 1 ); // capacity is some starter value, likely 1
v.clear(); // size is 0 but capacity is still same as before!

v = { 1, 2, 3, 4 }; // size is 4, and lets assume capacity is 4.
v.push_back( 5 ); // capacity grows - let's assume it grows to 6 (1.5 factor)
v.push_back( 6 ); // no change in capacity
v.push_back( 7 ); // capacity grows - let's assume it grows to 9 (1.5 factor)
// and so on
v.pop_back(); v.pop_back(); v.pop_back(); v.pop_back(); // capacity stays the same