调整大小后的矢量容量

时间:2015-12-05 05:50:16

标签: c++ vector

在下面的程序中,我只创建一个空向量,然后调整为5个元素,然后调整为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 $

1 个答案:

答案 0 :(得分:3)

如果请求的大小大于当前容量,则容量通常会加倍,直到它足够大。这种规模的倍增使得在O(1)上的摊销成本保持不变。