是否可以计算出 std::vector 扩展其数组大小的频率

Is it possible to figure out how often std::vector expands the size of its array?

本文关键字:数组 频率 扩展 vector 计算 std 是否      更新时间:2023-10-16

我胡思乱想弄清楚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)