为矢量矢量分配内存

Abd*_*rad 1 c++ vector

我正在尝试为向量向量保留空间,但它不起作用并抛出以下错误:

terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
Run Code Online (Sandbox Code Playgroud)

每次我使用足够大的数字.我所拥有的最小版本如下:

#include <vector>
#include <iostream>
using namespace std;


int main(){

  int base;
  cout << "Enter Base: ";
  cin >> base;

  int dimension;
  cout << "Enter Dimension: ";
  cin >> dimension;

  int perms = 1;
  for(int i=0; i<dimension; i++){
    perms *= base;
  } // This gets the number of permutations with repetition

  int length;
  cout << "Enter Length: ";
  cin >> length;

  float structSize = 1.0;

  for(float i=0.0; i<length; i++){
    structSize *= perms-i;
    structSize /= (i+1.0);
  } // This gets the number of combinations

  vector< vector< vector<double> > > allStructs;
  allStructs.reserve(structSize); 

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

它应该适用于大型structSizes,但是在base = 3,dimension = 4,length = 6时失败,这使得structSize = 324,540,216.这可能有用吗?

Xir*_*ema 5

你需要考虑你的记忆力.

它应该适用于大型structSizes,但是在base = 3,dimension = 4,length = 6时失败,这使得structSize = 324,540,216.这可能有用吗?

所以你在抽象层面上正在做的是分配一个包含324,540,216一个vector<vector<double>>对象实例的数据结构.

这是我们对vector对象的了解:

  • 它的大小必须至少为16个字节; 它需要存储一个指针,它在64位架构中可能是8个字节,它需要存储一个大小,也可能是8个字节.
  • 它的大小可能会大得多,因为从实例化最后一个vector<double>对象的那一刻起,每次创建一个对象时,它将消耗另一个[至少 - ] 16个字节.

所以从表面上看,你的allStructs.reserve(structSize)通话分配5千兆字节.它可能分配的不止于此,因为矢量元数据的大小很可能大于16个字节.