vector memory allocation strategy(向量内存分配策略)
问题描述
我写了一小段代码来确定向量中的内存分配是如何完成的.
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
和/或 resize
的 vector
If you need to rely on how many items are allocated you should use reserve
and/or resize
methods of vector
这篇关于向量内存分配策略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:向量内存分配策略


- 如何对自定义类的向量使用std::find()? 2022-11-07
- STL 中有 dereference_iterator 吗? 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 从python回调到c++的选项 2022-11-16
- Stroustrup 的 Simple_window.h 2022-01-01
- 静态初始化顺序失败 2022-01-01
- C++ 协变模板 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 近似搜索的工作原理 2021-01-01