C++ large array of vectors

I'm having some troubles with a large array of vectors in C++. Basicaly I wan't an array of 2 millions elements, and each elements is a vector<int> (It's for building an adjacency list).

So when I do vector<int> myList[10] it works great, but when i do vector<int> myList[2000000] it does not work and I don't know why.

I tried to do unsigned long int var = 2000000; vector<int> myList[var]; unsigned long int var = 2000000; vector<int> myList[var]; but still the same error. (I don't know what is the error, my program just crash)

If you have any idea,

Thanks


There's a big difference between heap and stack memory. The heap is the nice big space where you can dynamically allocate gigabytes of memory - the stack is much more constrained in terms of allocation size (and is determined at compile time).

If defining a local variable, that means it lives on the stack (like your array). With 2 million elements, that's at least 2MB being allocated (or assuming ~24B of stack usage per vector, more like 48MB), which is quite a lot for the stack, and likely causes the crash. Dynamically allocating an array of vector s (or preferably just allocating a vector of vector s) ensures that the bulk of the memory is being allocated from the heap, which might prevent this crash.

You can also increase the size of the stack using compiler flags, but that's generally not preferable to just dynamic allocation.


This is helpfull

Dynamically allocate memory for my_List . or

Declare your array of vector of int's( my_List ) as a global variable and size a `const. Thier storage locations are by design big enough to allocate such large mermory size.

For local variable, the stack segment might be to small to allocate 2e6*24B.

链接地址: http://www.djcxy.com/p/79808.html

上一篇: 如何获得可用系统内存的大小?

下一篇: C ++大量向量