0

I have an array, int dims[n], where n means dims, for example n=3 means there are 3 dims.

dims[i] stores the corresponding length of the dim.

I want to create an array, arr[dims[0]][dims[1]][...][dims[n]], is there any good methods?

(dims[n] is not sure when the code is compiled, I am not able to define a certain format of arr)

I need the array for a function with argument double*, the function will read an n-dimensional array from file and could not put data into a 1-dimensional array (in this case, it will report an memory error and I am not able to reconfigure the function).

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
houcz
  • 11
  • 1
  • https://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c – πάντα ῥεῖ Mar 13 '22 at 16:55
  • 1
    @πάνταῥεῖ thats not the question at all, OP wants an N dimensional array where N is only known at run time – pm100 Mar 13 '22 at 16:56
  • 3
    create a single array length dim[0] * dim[1] * dim[2] ... * dim[n]. then calculate the offsets yourself – pm100 Mar 13 '22 at 16:57
  • 2
    Whenever you think "dynamic array" your next though should almost always be `std::vector`. – Some programmer dude Mar 13 '22 at 17:00
  • You can not allocate an array with unknown number of dimensions, can't even give it a type. So as pm100 suggests you have to make a 1 dimesional array and compute indexes yourself. I recommend putting that in a class that takes `std::vector dims` in the constructor and provides an `operator[](const std::vector)` for access to elements. You can add support for ranges, views, spans, slizes as well. – Goswin von Brederlow Mar 13 '22 at 17:02
  • When I use python, numpy package, I could use a = np.zeros((1, 2, 3)) to create an array with shape (1, 2, 3). I mean, how should I do this in C++? – houcz Mar 13 '22 at 17:06
  • The shape is of course a certain number, dims will be generated in the previous code. Then I will need to storage some data with such an array. – houcz Mar 13 '22 at 17:07
  • 1
    "how should I do this in C++" You implement a class that does this, or find a third-party library that has already implemented one for you. No such class exists in the C++ standard library, if that's what you are asking. – Igor Tandetnik Mar 13 '22 at 17:32
  • The closest thing to numpy like matrices and tensors in c++ would be a library called Eigen which has dynamically sized objects I believe (https://eigen.tuxfamily.org/). If that doesn't work for you, the simplest thing would be to use a flat std:vector with some index calculation routines packaged into a class. – Tim Seguine Mar 13 '22 at 18:09
  • Use `std::valarray` and related functions. With that you can easily do it. – A M Mar 14 '22 at 15:47

0 Answers0