开发者

Create a big array in C++ [duplicate]

开发者 https://www.devze.com 2023-01-05 13:16 出处:网络
This question already has answers here: Closed 12 years ago开发者_Go百科. Possible Duplicate: Segmentation fault on large array sizes
This question already has answers here: Closed 12 years ago开发者_Go百科.

Possible Duplicate:

Segmentation fault on large array sizes

Hi all

I am trying to create a very big array in the VS 2010 using C++.

When I try to create a array like below

int dp[4501][4501]
or
int dp[1000][1000]

It threw an exception "Stack Overflow" Then I change it to:

int dp[100][100]

everything is fine.

So if I want to create a big array like above, what should I do?

Best Regards,


Use dynamic allocation or the STL. There was a recent thread about a very similar question. See this.


You should use dynamic allocation:

typedef std::vector<int> int_vector;
int_vector dp(10000);

A double array can be simulated by nesting arrays:

typedef std::vector<int_vector> int_double_vector;
int_double_vector dp(4501, int_vector(4501));


Put it on the heap.


If you want to avoid new[], or avoid using std::vector, make the array global. This will put the array on heap and stack overflow will not occur.


Text from Parashift faq : Why should I use container classes rather than simple arrays?

EDIT:

Take a look at stackoverflow threads:

When would you use an array rather than a vector/string? Why use iterators instead of array indices?


Your stack has overflowed with too many bits. You must drain them. Preferably onto a heap of other bits. I suggest /F67108864. The /F stands for "F'ing hell why is the stack so small compared to the heap?". The 67108863 is arbitrary.


Your declaration looks a bit as if dp will be used as a matrix. In that case, a dedicated (dense) matrix class such as boost::numeric::ublas::matrix is the simplest solution, easier and more local than a vector of vectors. If the matrix is sparsely populated, use a sparse matrix class instead.


So if I want to create a big array like above, what should I do?

Avoid using the stack for these cases (in other words, avoid creating arrays like these which aren't heap-allocated when working inside a function). Just to give you an idea, my thread-local stack is only 16 kilobytes large. 4501 * 4501 * 4 (assuming 4 bytes per int) = ~81 megabytes.

Consider something like this instead:

typedef vector<int> Row;
typedef vector<Row> Matrix;
Matrix dp(4501, Row(4501) );

If you want to create a 10x50 matrix:

Matrix dp(10, Row(50) );

You can use this just like your normal dp array had it not overflowed the stack. This one will be allocated and automatically deallocated to/from the heap so that you don't have to worry about stack overflow when using it.

dp[5][10] = 123;

Good luck!

[Edit] There are also matrix solutions in boost worth looking into but suggesting boost might be a bit premature given the nature of the topic.

0

精彩评论

暂无评论...
验证码 换一张
取 消