vector的reallocation

每一个面试题都需要用心

#include <iostream>
#include <vector>
using namespace std;

class pt
{
public:
    pt()
    {
        cout << "construction" << endl;
    }

    pt(const pt &obj)
    {
        cout << "copy construction" << endl;
    }

    ~pt()
    {
        cout << "destruction" << endl;
    }
};

int main()
{
    pt a;
    pt b;
    vector<pt> vec;

    vec.push_back(a);
    vec.push_back(b);
    vec.push_back(a);
    vec.push_back(b);

    cout << vec.size() << endl;
}
输出答案:

construction
construction
copy construction
copy construction
copy construction
destruction
copy construction
copy construction
copy construction
destruction
destruction
copy construction
4
destruction
destruction
destruction
destruction
destruction
destruction

输出答案分析:
  1. vector可用空间不足时空间增长算法。增长到最近的2^n大小,即按1、2、4、… 、增长。
  2. vector空间重新分配时采用copy构造移动以前的元素,然后集中destruction。
参考:

vector push_back()官方帮助文档
Add element at the end
Adds a new element at the end of the vector, after its current last element. The content of val is copied (or moved) to the new element.

This effectively increases the container size by one, which causes an automatic reallocation of the allocated storage space if -and only if- the new vector size surpasses the current vector capacity.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值