2016-08-02 58 views
1

我想保留空间向量的向量的载体,但它不工作,并抛出以下错误:分配内存为载体

terminate called after throwing an instance of 'std::bad_alloc' 
    what(): std::bad_alloc 

每次我用一个足够大的数。的我有一个最小的版本下面是:

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

应该为大structSizes工作,但在基部= 3,尺寸= 4,长度= 6这使得structSize = 324540216失败。这有可能工作吗?

+2

是的,这是可能的 - 增加更多的内存到你的电脑 – Slava

+2

你有没有做这个数字需要多少内存? –

+0

你真的要存储每个结果吗?你不能只是迭代结果吗? – Jarod42

回答

5

你需要考虑你的记忆使用。

It should work for large structSizes, but fails at base=3, dimension=4, length=6 which makes structSize=324,540,216. Is it possible for this to work?

所以,你在做什么,在抽象的层面,被分配一个包含vector<vector<double>>对象的324,540,216实例的数据结构。

下面是我们所知道的vector对象:

  • 它的大小必须至少为16个字节;它需要存储一个指针,该指针在64位体系结构中可能是8个字节,并且需要存储一个大小,该大小也可能是8个字节。
  • 它的大小可能会大得多,因为从实例化最后一个对象的那一刻起,每次创建对象时都会消耗另一个[at-least-] 16个字节。

所以就在它的表面上,您的allStructs.reserve(structSize)调用分配了5千兆字节。它可能会分配更多,因为矢量元数据的大小可能会大于16个字节。

+0

从技术上讲,如果矢量的大小都是向量数组的索引,则矢量的大小没有限制。即使在更现实的一面,我看到一次内部指针指向数据的'std :: string'的实现,并将大小和容量存储在mData [-4]和mData [-8]中,这意味着'printf(“%s”,myStdString)'实际上可以工作。 –

+0

@MooingDuck公平点,尽管在用户试图实际存储和处理每个索引中的值时,它仍会导致内存分配问题。 – Xirema

2

声明你的StructSize为double StructSize = 1.0;那么它应该“逻辑”的工作。

但是,reserve()可能无法正常工作,因为您的PC可能会受到内存限制。