vector的reallocation

xiaoxiao2021-02-28  93

每一个面试题都需要用心

#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

输出答案分析:

vector可用空间不足时空间增长算法。增长到最近的2^n大小,即按1、2、4、… 、增长。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.

转载请注明原文地址: https://www.6miu.com/read-47623.html

最新回复(0)