矢量内存分配策略 [英] vector memory allocation strategy

查看:83
本文介绍了矢量内存分配策略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  #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编译这些结果:



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 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

  capacity = capacity * 2 ; 

正如你所看到的,这是两个非常不同的结果。
为什么这样呢?是仅仅依赖于编译器还是对其他因素沉迷?



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

解决方案

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



如果你需要依赖于分配多少项,你应该使用 方法 和 b

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;
}

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 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

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?

解决方案

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

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆