C++ large array of vectors

前端 未结 2 1282
情歌与酒
情歌与酒 2021-01-17 08:29

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

相关标签:
2条回答
  • 2021-01-17 08:44

    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.

    0 讨论(0)
  • 2021-01-17 08:57

    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 vectors (or preferably just allocating a vector of vectors) 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.

    0 讨论(0)
提交回复
热议问题