-2

My simulation tries to predict the demand on a system for a long period of time ... the output results in a very large 4D array (I use the 4 dimensions to minimise the chance of an error when the data is written to the array i.e. I can understand it better this way!).

The array size will be 25x4x3x20000 and I need it to be at least an (unsigned int) but I know that the stack can't handle this amount of data.

unsigned int ar[25][4][3][2000];

I have been looking around and found different solutions. However I am still undecided on which one to implement. So my question is: which one is better in term of performance and good practice:

  1. Use a vector of arrays: as described in stackoverflow.com/questions/18991765 ... But then any idea on how to convert for a 4D dimensions?

std::vector< std::array<int, 5> > vecs; vecs.reserve(N);

  1. Use a 4D vector and push_back(): I didn't use this because I know the final size of the array and I wanted to prevent many push_backs operations.
  2. Create the array on the heap: as described in stackoverflow.com/questions/675817

Any other suggestion is appreciated!

Jid
  • 1

1 Answers1

1

The biggest problem is that [2000] in the final dimension. Just make that dynamic.

Have your 3D array as such:

using arr3d = std::array<std::array<std::array<unsigned int, 25>, 4>, 3>;

and then the vector for the fourth dimension:

std::vector<arr3d> ar;
ar.reserve(N); // for optimization
DeiDei
  • 10,205
  • 6
  • 55
  • 80
  • You've rearranged the order of the array dimensions. What you have looks like `ar[2000][3][4][25]` – Blastfurnace Oct 09 '18 at 17:35
  • @DeiDei great I will try as you have suggested ... In this case if I want to use a pointer to manipulate my array I create it to the vector `vector *ptr_ar = &ar;` then I can access the array easily with `ptr_ar->at(1)` ... Is that correct? – Jid Oct 09 '18 at 17:38
  • 1
    Yes, sure. But you might wanna look into references, e.g. `vector& ref_ar = ar;` and then `ref_ar.at(1)`. It's just safer this way. Also make sure you fix the dimensions as @Blastfurnace mentioned. I'll edit the answer in a bit. – DeiDei Oct 09 '18 at 17:41