vector空间的申请规则

当申请空间为20的capacity,如果超过该capacity,则自动扩展为当前capacity的一倍(20*2 = 40);
若这40的capacity也被用完,则继续自动扩展为当前的一倍(40*2 = 80)

测试代码及结果如下

#include 
#include 
#include 

int main()
{
    std::vector vec(20);
    vec[0] = 1;
    printf("size:%d\n", vec.size());
    printf("max_size:%d\n", vec.max_size());
    printf("capacity:%d\n", vec.capacity());
    printf("====before push_back====\n");
    vec.push_back(1);
    printf("size:%d\n", vec.size());
    printf("max_size:%d\n", vec.max_size());
    printf("capacity:%d\n", vec.capacity());
    printf("====after push_back 1 item====\n");
    for (int i = 0; i < 20; i++)
    {
        vec.push_back(1);
    }
    printf("size:%d\n", vec.size());
    printf("max_size:%d\n", vec.max_size());
    printf("capacity:%d\n", vec.capacity());
    printf("====after push_back 21 item====\n");
}

结果:
size:20
max_size:-1
capacity:20
====before push_back====
size:21
max_size:-1
capacity:40
====after push_back 1 item====
size:41
max_size:-1
capacity:80
====after push_back 21 item====
 

你可能感兴趣的:(总结,c++)