【问题标题】:Is it possible to figure out how often std::vector expands the size of its array?是否可以计算出 std::vector 扩展其数组大小的频率?
【发布时间】:2015-04-19 04:49:21
【问题描述】:

我正在四处寻找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/) 的地方,我该怎么做?我真正想做的就是看看底层数组如何随着元素的逐一添加而周期性地“跳跃”。

【问题讨论】:

  • 使用 .capacity() 获取在向量调整大小之前可以存储的元素数量。如果我不得不猜测,大多数向量实现都使用加倍策略:每次空间不足时,向量的容量都会加倍。这确保了平均 O(1) 插入时间。
  • @Hillary Rodham Clinton 请显示所有程序输出。:)

标签: c++ vector


【解决方案1】:

您应该检查myVec.capacity()

【讨论】:

    【解决方案2】:

    当你将一个值压入向量时,它的大小会增加一。当大小达到向量容量时,分配更多内存,容量翻倍。

    您可以致电myVec.capacity()查看容量。因此,为了找出分配了多少内存,您可以执行以下操作:

    myVec.capacity() * sizeof(int)
    

    【讨论】:

    • 小问题:增加向量的容量并不一定会使容量翻倍,尽管这在实践中是一种相当常见的策略。
    猜你喜欢
    • 2012-07-10
    • 2014-05-10
    • 1970-01-01
    • 1970-01-01
    • 2015-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多