vector的reallocation

来源:互联网 发布:php jsonp callback 编辑:程序博客网 时间:2024/06/06 02:20

每一个面试题都需要用心

#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.