How to create a multidimensional array dynamic to the number of dimensions?

Let me preface by saying I have extensive experience working with Python.

I am looking to build the equivalent of a NumPy array (Python) in C++.

My issue is trying to create a Multidimensional array in C++ in such a manner that the number of dimensions isn't specified within the array creation method, but provided as an argument to this method.

For example, I want to be able to do something like this:

struct Array {
Array(int ndim, int dim1_size, int dim2_size......) {
// ndim specifies the number of dimensions in array
// ndim = 4 --> arr = Array[3][4][2][5]
// ndim = 2 --> arr = Array[5][8]
......
}

What is the most elegant way to do this? I know one solution is to add the elements to a flattened 1D array, but this makes matrix multiplication etc difficult for me to implement. I would prefer to preserve the shape of the array, to keep my understanding of matrix operations as organic as possible.

Maybe a pointer of pointers solution? But I am not quite sure how to formulate the code for that.
Last edited on
BreakingTheBadBread wrote:
I know one solution is to add the elements to a flattened 1D array, but this makes matrix multiplication etc difficult for me to implement.

For an arbitrary number of dimensions (i.e. higher than 2) I think a flattened 1d array is probably your best bet.

You then need just a function that transforms your i,j,k,l... indices to a 1-d index, n. It will be that function that does all the work.

The other alternative might be template arrays, but I think that would be considerably harder.

If you only use 2-d arrays (implied by your matrix multiplication) then the nearest thing to a NumPy array would be valarray<valarray<double>>.
Last edited on
I agree about using flattened 1d array is best in this case in conjunction with variadic templated class/operator() so that the number of dimensions/dimension size can be specified for the constructor and the indexes for operator().
Topic archived. No new replies allowed.