2015-12-05 121 views
1

在下面的程序中,我只創建一個空矢量,然後調整爲5個elelemnts,然後調整爲8個元素。調整大小後的矢量容量

但是,在將其大小調整爲8個元素後,容量顯示爲10。上一次調整大小後,爲什麼容量10而不是8

以下是代碼。我已經評論了問題出在哪裏。

//This program has vector method resize() 
//2015-12-05 Sat 12:06 AM 
using namespace std; 
#include<iostream> 
#include<vector> 

int main() 
{ 
    vector<int> vec1; 
    //Initial empty vector 
    cout << "Printing what an empty vector has..." << endl; 
    cout << "Size: " << vec1.size() << endl; 
    cout << "Capacity: " << vec1.capacity() << endl;  
    cout << endl << endl; 

    //Resize to 5, without giving any value. 
    cout << "Printing after resizing to 5 elements..." << endl; 
    vec1.resize(5); 
    cout << "Size: " << vec1.size() << endl; 
    cout << "Capacity: " << vec1.capacity() << endl; 
    cout << endl << endl; 

    //Resize to 8, with value also this time 
    //ISSUE HERE, WHY IS CAPACITY PRINTED AS '10', instead of '8' 
    cout << "Printing after resizing to 8, and also giving values..." << endl; 
    vec1.resize(8, 15); 
    cout << "Size: " << vec1.size() << endl; 
    cout << "Capacity: " << vec1.capacity() << endl; 
    cout << endl; 
    return 0; 
} 

下面是輸出:

user $ ./a.out 
Printing what an empty vector has... 
Size: 0 
Capacity: 0 
Elements: 

Printing after resizing to 5 elements... 
Size: 5 
Capacity: 5 
Elements: 0 0 0 0 0 

Printing after resizing to 8, and also giving values... 
Size: 8 
Capacity: 10 
Elements: 0 0 0 0 0 15 15 15 
user $ 
+4

'size'是元素的數量。容量是在需要重新分配之前它可以存儲多少個元素。 –

+1

http://stackoverflow.com/questions/6296945/size-vs-capacity-of-a-vector – wizurd

回答

3

如果請求的大小比當前的容量越大,容量通常加倍,直到它足夠大。這個規模的翻倍是保持O(1)增長的攤銷成本。

+0

沒問題,所以程序員無法控制容量?我只能改變尺寸? – sps

+2

@sps'reserve'和'shrink_to_fit'可以改變容量。 –