是否可以计算出 std::vector 扩展其数组大小的频率
Is it possible to figure out how often std::vector expands the size of its array?
我胡思乱想弄清楚std::vector
如何管理其底层数组的大小。我知道它会进行某种大小调整,例如,当调用以尝试在底层数组已满时添加元素时,创建一个大小是前一个数组两倍的新数组并将旧值复制到其中(或类似的东西)。
所以我只是做了
#include <iostream>
#include <vector>
int main()
{
std::vector<int> myVec;
for (int i = 1; i < 10000; ++i)
{
myVec.push_back(i);
std::cout << i << " elements in vector; size of vector is " << sizeof(myVec) << " bytes." << std::endl;
}
return 0;
}
正在打印出来
1 elements in vector; size of vector is 28 bytes.
2 elements in vector; size of vector is 28 bytes.
3 elements in vector; size of vector is 28 bytes.
4 elements in vector; size of vector is 28 bytes.
5 elements in vector; size of vector is 28 bytes.
6 elements in vector; size of vector is 28 bytes.
7 elements in vector; size of vector is 28 bytes.
8 elements in vector; size of vector is 28 bytes.
9 elements in vector; size of vector is 28 bytes.
10 elements in vector; size of vector is 28 bytes.
11 elements in vector; size of vector is 28 bytes.
12 elements in vector; size of vector is 28 bytes.
13 elements in vector; size of vector is 28 bytes.
14 elements in vector; size of vector is 28 bytes.
15 elements in vector; size of vector is 28 bytes.
16 elements in vector; size of vector is 28 bytes.
17 elements in vector; size of vector is 28 bytes.
18 elements in vector; size of vector is 28 bytes.
19 elements in vector; size of vector is 28 bytes.
20 elements in vector; size of vector is 28 bytes.
21 elements in vector; size of vector is 28 bytes.
22 elements in vector; size of vector is 28 bytes.
23 elements in vector; size of vector is 28 bytes.
24 elements in vector; size of vector is 28 bytes.
25 elements in vector; size of vector is 28 bytes.
26 elements in vector; size of vector is 28 bytes.
27 elements in vector; size of vector is 28 bytes.
28 elements in vector; size of vector is 28 bytes.
29 elements in vector; size of vector is 28 bytes.
30 elements in vector; size of vector is 28 bytes.
31 elements in vector; size of vector is 28 bytes.
32 elements in vector; size of vector is 28 bytes.
etcetera
我意识到这是因为我正在查看向量的大小,它包含一个指向底层数组的指针,因此向量的大小不包括底层数组的大小。鉴于我没有看到任何可以直接访问底层数组 (http://www.cplusplus.com/reference/vector/vector/) 的地方,我该怎么做我想要做的事情?我真正想做的是看看底层数组在元素逐一添加时如何周期性地"跳跃"大小。
你应该
检查myVec.capacity()
。
将值推送到向量时,其大小将增加 1。当大小达到矢量容量时,将分配更多内存,并且容量加倍。
您可以通过调用 myVec.capacity()
来检查容量。因此,为了找出分配了多少内存,您可以执行以下操作:
myVec.capacity() * sizeof(int)
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用 for 循环 c++ 确定与数组中特定频率匹配的值的函数
- 如何使用二维数组来计算和存储来自其他数组的值的频率
- 我如何在数组中找到特定值的频率
- 给定索引 i,j(j>=i) 如何在子数组(i,j)上找到 A[j] 的频率?
- 是否可以计算出 std::vector 扩展其数组大小的频率
- 检查数组值连续出现的频率
- 计算 C 数组中三元组的频率以进行索引
- 计数数组中元素的频率
- 给定一个范围,我必须计算数组中数字的频率.给定的解决方案是否有效