vector push_back 超过 capacity 时产生的内存拷贝问题

本文介绍了C++ std::vector在push_back超过capacity时的内存拷贝和扩展机制。当vector达到其capacity,插入新元素会触发扩展,导致原有元素拷贝到新分配的内存中,容量翻倍。这个过程可能带来性能影响,需要注意深拷贝和浅拷贝的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

根据 C++ Reference 的官方解释:http://www.cplusplus.com/reference/vector/vector/

Just like arrays, vectors use contiguous storage locations for their elements, which means that their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in arrays. But unlike arrays, their size can change dynamically, with their storage being handled automatically by the container.
Internally, vectors use a dynamically allocated array to store their elements. This array may need to be reallocated in order to grow in size when new elements are inserted, which implies allocating a new array and moving all elements to it. This is a relatively expensive task in terms of processing time, and thus, vectors do not reallocate each time an element is added to the container.

从此可以看出,std::vector 具有以下特点:

  • 内部使用数组的方式进行数据存储,内存连续</
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值