vector的reserve的作用
之前提到vector中不断的push_back,会进行内存的重新自动分配的问题
(详见:https://blog.csdn.net/hl_zzl/article/details/84798804 )
为了避免重新分配内存带来的问题,vector提供了reserve函数。
std::vector::reserve
void reserve (size_type n);
Request a change in capacity
Requests that the vector capacity be at least enough to contain n elements.
If n is greater than the current vector capacity, the function causes the container to reallocate its storage increasing its capacity to n (or greater).
In all other cases, the function call does not cause a reallocation and the vector capacity is not affected.
This function has no effect on the vector size and cannot alter its elements.
reserve的作用是更改vector的容量(capacity),使vector至少可以容纳n个元素。
如果n大于vector当前的容量,reserve会对vector进行扩容。其他情况下都不会重新分配vector的存储空间
Demo:对比使用reserve的区别
说明:在main中声明了两个vector,vecInt为默认初始化,vecIntB使用capacity初始化其容量为100。分别对vetIntA和vecIntB进行同样的操作:
①把0~99依次push_back到vector中,
②在push_back的过程中观察vector的容量capacity是否发生变化。
#include <iostream>
#include <vector>
#include <stdint.h>
using namespace std;
void growPushBack(vector<int> &vec, uint16_t