vector 的 capacity 增长

在对 vector 容器 push_back 操作时,其capacity 会以怎样的大小进行扩容呢?

cpp 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <string>

int main()
{
    std::vector<std::string> stringVec;
    printf("1, capacity of stringVec is %u\n", stringVec.capacity());

    stringVec.push_back("11");
    stringVec.push_back("22");
    printf("2, capacity of stringVec is %u\n", stringVec.capacity());

    stringVec.push_back("33");
    printf("3, capacity of stringVec is %u\n", stringVec.capacity());    
    stringVec.push_back("44"); 
    return 0;
}

可以看出在容器空时其 capacity 的大小为0,此时容器内并没有元素;在 push_back 2次后,其 capacity 的大小为 2;再 push_back 一次时,此时容器当中应该有 3 个元素,而 capacity 的大小为 4,可以看出 vector 的 capacity 的每次增长是当前大小的 2 倍。结合源码看一下:

容量不够时,扩容

最关键的就是要申请的大小 __len 的值是多少?用 GDB 跟踪一下可以看到其大小:

其求值是这句 const size_type __len = size() + std::max(size(), __n); size() 取的是当前元素的个数,而入参 __n = 1, 所以 __len = size() + size(),这不就是 2 个 size() 吗?不过如果是首次 push_back 的话,__len = 1,因为此时 size() = 0。可以验证一下:

cpp 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <string>

int main()
{
    printf("__cplusplus = %d\n", __cplusplus);
    std::vector<std::string> stringVec;
    printf("1, capacity of stringVec is %u\n", stringVec.capacity());

    stringVec.push_back("11");
    printf("2, capacity of stringVec is %u\n", stringVec.capacity());

    stringVec.push_back("22");
    printf("3, capacity of stringVec is %u\n", stringVec.capacity());

    stringVec.push_back("33");
    printf("4, capacity of stringVec is %u\n", stringVec.capacity());    
    stringVec.push_back("44"); 
    return 0;
}

首次 push_back 后 vecotr 的 capacity = 1,之后的增长则是为当前 size() 的 2 倍。

相关推荐
2301_803554521 天前
Pimpl(Pointer to Implementation)设计模式详解
c++·算法·设计模式
John_ToDebug1 天前
从零开始:在 Windows 环境下拉取并编译 Chrome 源码全纪录
c++·chrome·windows
Dream it possible!1 天前
LeetCode 面试经典 150_图的广度优先搜索_蛇梯棋(93_909_C++_中等)(广度优选搜索)
c++·leetcode·面试·广度优先
进击的荆棘1 天前
C++起始之路——类和对象(上)
开发语言·c++
草莓熊Lotso1 天前
《算法闯关指南:动态规划算法--斐波拉契数列模型》--04.解码方法
c++·人工智能·算法·动态规划
1nv1s1ble1 天前
[c++] cpp快速添加sqlite_orm
c++·sqlite
陶陶name1 天前
Metal Compute Pipeline:Metal-C++ 环境配置与简单算子实现
开发语言·c++
凌康ACG1 天前
Sciter之子线程更新UI(八)
c++·sciter
你的冰西瓜1 天前
C++23 新特性详解:相较于 C++20 的主要改进
开发语言·c++·stl·c++23
浔川python社1 天前
C++ 之父中国行・40 周年城市站 —— 北京 & 上海开发者见面日报名链接暂不对外开放公告
c++