C ++向量大数组 [英] C++ large array of vectors

查看:88
本文介绍了C ++向量大数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用C ++中的大量矢量时遇到了麻烦.基本上,我不会有200万个元素的数组,每个元素都是一个 vector< int> (用于建立邻接表).

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).

所以当我做 vector< int>myList [10] 效果很好,但是当我执行 vector< int>时,myList [2000000] 无效,我也不知道为什么.

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.

我试图做 unsigned long int var = 2000000;向量< int>myList [var]; ,但仍然是相同的错误.(我不知道这是什么错误,我的程序崩溃了)

I tried to do 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)

如果您有任何想法,

谢谢

推荐答案

堆和堆栈内存.堆是一个不错的大空间,您可以在其中动态分配GB的内存-堆栈在分配大小方面(并且在编译时确定)受到更多限制.

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).

如果定义局部变量,则意味着它位于堆栈中(如数组).拥有200万个元素,则至少分配了2MB的空间(或假设每个向量的堆栈使用量约为24B,更像是48MB),这对于堆栈来说是相当多的,并且很可能导致崩溃.动态分配 vector s的数组(或最好只是分配 vector s的 vector )可确保从中分配大量内存堆,这可以防止此崩溃.

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.

这篇关于C ++向量大数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆