向量内存分配策略

2021-12-21 00:00:00 memory-management vector c++

我写了一小段代码来确定向量中的内存分配是如何完成的.

i wrote a little piece of code to determine, how memory allocating in a vector is done.

#include <iostream>
#include <vector>
using namespace std;
int main ()
{
  vector<unsigned int> myvector;
  unsigned int capacity = myvector.capacity();

  for(unsigned int i = 0; i <  100000; ++i) {
    myvector.push_back(i);
    if(capacity != myvector.capacity())
    {
      capacity = myvector.capacity();
      cout << myvector.capacity() << endl;
    }
  }
  return 0;
}

我在 Ubuntu 上使用 Visual Studio 2008 和 g++ 4.5.2 编译并得到了以下结果:

I compiled this using Visual Studio 2008 and g++ 4.5.2 on Ubuntu and got these results:

Visual Studio:

1 2 3 4 6 9 13 19 28 42 63 94 141 211 316 474 711 1066 1599 2398 3597 5395 8092 12138 18207 4 5 6 10 4 5 4 5 5 5 5 5 5 2 106

1 2 3 4 6 9 13 19 28 42 63 94 141 211 316 474 711 1066 1599 2398 3597 5395 8092 12138 18207 27310 40965 61447 92170 138255

capacity = capacity * 1.5;

g++:

1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 131072

1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 131072

capacity = capacity * 2;

如您所见,这是两种截然不同的结果.为什么会这样?是只依赖于编译器还是依赖于其他因素?

As you can see, these are two very different results. Why is this like that? Is it only depending on the compiler or is it addicted to other factors?

即使对于大量元素,继续将容量增加一倍真的有意义吗?

Does it really make sense to keep on with doubling the capacity, even for large numbers of elements?

推荐答案

vector 如何增长是实现定义的.所以在插入相同数量的元素后,可以使用不同的策略导致不同的容量

How the vector is growing is implementation defined. So different strategies can be used resulting in different capacity after inserting the same count of elements

如果你需要依赖分配了多少项,你应该使用 reserve 和/或 resizevector

If you need to rely on how many items are allocated you should use reserve and/or resize methods of vector

相关文章