我正在尝试为向量向量保留空间,但它不起作用并抛出以下错误:
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.这可能有用吗?
你需要考虑你的记忆力.
它应该适用于大型structSizes,但是在base = 3,dimension = 4,length = 6时失败,这使得structSize = 324,540,216.这可能有用吗?
所以你在抽象层面上正在做的是分配一个包含324,540,216一个vector<vector<double>>对象实例的数据结构.
这是我们对vector对象的了解:
vector<double>对象的那一刻起,每次创建一个对象时,它将消耗另一个[至少 - ] 16个字节.所以从表面上看,你的allStructs.reserve(structSize)通话分配5千兆字节.它可能分配的不止于此,因为矢量元数据的大小很可能大于16个字节.