C++ Vector 内存分配

本文通过一个具体的C++示例展示了std::vector容器如何在插入新元素导致当前容量不足时自动扩展其容量。实验中使用了一个包含拷贝构造函数和析构函数的日志输出类Point来观察vector在扩容过程中的行为。

vector会预先分配比当前数据大的一个空间,如果有新的元素进来填满了这个空间,就又会继续分配。

分配策略一般是1,2,4,8,16...

直接上代码:


#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <math.h>
#include <list>
#include <string>

using namespace std;

class Point
{
public:
    Point()
    {
        cout << "construction" << endl;
    }
    Point(const Point& p)
    {
        cout << "copy construction" << endl;
    }
    ~Point()
    {
        cout << "destruction" << endl;
    }
};

int main(int argc, const char * argv[])
{
    Point test[10];
    cout << "**************************" << endl;
    vector<Point> arr;
    for (int i = 0; i < 10; i++)
    {
        arr.push_back(test[i]);
        cout << "capacity=" << arr.capacity() << ",size=" << arr.size() << endl;
        cout << "--------------------------" << endl;
    }
    return 0;
}
结果:

construction

construction

construction

construction

construction

construction

construction

construction

construction

construction

**************************

copy construction

capacity=1,size=1

--------------------------

copy construction

copy construction

destruction

capacity=2,size=2

--------------------------

copy construction

copy construction

copy construction

destruction

destruction

capacity=4,size=3

--------------------------

copy construction

capacity=4,size=4

--------------------------

copy construction

copy construction

copy construction

copy construction

copy construction

destruction

destruction

destruction

destruction

capacity=8,size=5

--------------------------

copy construction

capacity=8,size=6

--------------------------

copy construction

capacity=8,size=7

--------------------------

copy construction

capacity=8,size=8

--------------------------

copy construction

copy construction

copy construction

copy construction

copy construction

copy construction

copy construction

copy construction

copy construction

destruction

destruction

destruction

destruction

destruction

destruction

destruction

destruction

capacity=16,size=9

--------------------------

copy construction

capacity=16,size=10

--------------------------

destruction

destruction

destruction

destruction

destruction

destruction

destruction

destruction

destruction

destruction

destruction

destruction

destruction

destruction

destruction

destruction

destruction

destruction

destruction

destruction



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值