vector的reserve的使用(避免内存重新分配以及内存分配的方式)


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
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值