向量内存分配策略

vector memory allocation strategy(向量内存分配策略)
本文介绍了向量内存分配策略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

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

这篇关于向量内存分配策略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

OpenGL transforming objects with multiple rotations of Different axis(OpenGL 变换不同轴多次旋转的对象)
GLFW first responder error(GLFW 第一响应者错误)
SOIL not linking correctly(SOIL 连接不正确)
Core profile vs version string? Only getting GLSL 1.3/OGL 3.0 in mesa 10.0.1(核心配置文件与版本字符串?在 mesa 10.0.1 中只获得 GLSL 1.3/OGL 3.0)
What is the range of OpenGL texture ID?(OpenGL 纹理 ID 的范围是多少?)
How taxing are OpenGL glDrawElements() calls compared to basic logic code?(与基本逻辑代码相比,OpenGL glDrawElements() 调用的繁重程度如何?)