C++中vector的capacity和size的区别 您所在的位置:网站首页 capacity和capable区别 C++中vector的capacity和size的区别

C++中vector的capacity和size的区别

2024-03-18 22:53| 来源: 网络整理| 查看: 265

vector中 capacity是指最少要多少元素才会使容器重新分配,reserve()可以设置capacity值。 size是指容器中有多少个元素,resize()可以修改容器大小。 乍一看,如果没有没有使用reserve()的话,vector的size和capacity应该是相同的,但是不见得。 代码1

int m,n; n=obstacleGrid.capacity(); m=obstacleGrid[0].capacity();

代码2

int m,n; n=obstacleGrid.size(); m=obstacleGrid[0].size();

我在一次刷leetcode的不同路径2时,发现了问题,虽然代码1和代码2中m,n的值相同,但后续使用m,n访问vector数组的时候,使用代码1报了错。

Line 922: Char 34: runtime error: reference binding to misaligned address 0xbebebebebebebebe for type 'value_type', which requires 4 byte alignment (stl_vector.h) 0xbebebebebebebebe: note: pointer points here

搜索之后说是数组越界,我反复检查并没有发现越界,而且代码1和代码2的m,n也是相同的。查询了两个函数的定义:

_NODISCARD size_type capacity() const noexcept { // return current length of allocated storage return (static_cast(this->_Myend() - this->_Myfirst())); } _NODISCARD size_type size() const noexcept { // return length of sequence return (static_cast(this->_Mylast() - this->_Myfirst())); }

但是也没有发现什么原因。。很困惑,因为我并没有使用如reserve()这种函数来修改capacity值。虽然没找到原因,但是以后使用的时候更留心了,如果只是取数组长度的话还是建议用size()就好。

追加: https://blog.csdn.net/sim0hayha/article/details/79050655 这个博客得知,即使不使用reserve(),capacity在存储不够的时候也会自动的扩充。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有