Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a very large vector of ints?

Tags:

c++

vector

Is there a way to do this in C++ without having things crash on runtime?

Right now I am declaring

vector<vector<int> > myvec(veclength);

How can I crank up veclength as high as it will go (properly)? Even at 10^7 it crashes when I should have more than enough computer memory.

like image 507
John Smith Avatar asked Apr 22 '12 12:04

John Smith


1 Answers

This should take take approximately 250 MiB of space1 (or less, depending on architecture) so memory definitely isn’t the problem here, and neither should max_size, which would be in the order of 1017 (≈ 2648+8+8).

I should mention that I corroborated these calculations by looking at the implementations of std::vectorin GCC' libstdc++ and LLVM's libc++, and by testing on a live system. The calculated values correspond 1:1 to the real implementations, and the OP’s code works flawlessly with veclength = 10e7.

I therefore conclude that the real cause is elsewhere.


1) Calculated by approximating the size of each individual vector by three 64 bit integers to denote begin pointer, size and capacity respectively, and assuming that an empty vector has a default capacity of 0. Actual implementations may differ but probably not by much.

like image 161
Konrad Rudolph Avatar answered Oct 05 '22 19:10

Konrad Rudolph