Exsa_N Exsa_N - 3 years ago 142
C++ Question

Inversion of a one-dimensional dynamic array into an N-dimensional

Help to understand the creation of the array: the task is to dynamically build an array with an arbitrary number of measurements and their arbitrary depth.
The input receives a one-dimensional array

int arr []
with an arbitrary (n) number of elements. For e.g we can create one-dimensional array like
int arr= new int[size]
, we can create two-dimensional array
int **arr= new int*[size]
and so on, but how can we create it when we dont'n know how many dimensions? I just started to learn C++ so I can't use object-oriented programming and vectors

Answer Source

As some of these commenters suggested, one thing you can do is create a large one-dimensional array instead of a multi-dimensional array, e.g.

int *arr = new int[wLength * zLength * yLength * xLength];

and instead of indexing this way arr[w][z][y][x] index like this: arr[w * zLength * yLength * xLength + z * yLength * xLength + y * xLength + x].

Of course if you want the type of N-dimensional arrays (given N is a constant expression), you can use a template with an overload like this:

template <typename T, int N>
struct NDimensionalArray {
    typedef typename NDimensionalArray<T, N-1>::Type *Type;

template<typename T>
struct NDimensionalArray<T, 0> {
    typedef T Type;

With that definition, you get these types:

std::is_same<NDimensionalArray<char, 1>::Type, char*>::value; // true
std::is_same<NDimensionalArray<char, 2>::Type, char**>::value; // true
std::is_same<NDimensionalArray<char, 3>::Type, char***>::value; // true

Encapsulated N-dimensional array class, for newing, deleting, and indexing into N-dimensional arrays, left as an exercise. (Hint: Use a std::array<unsigned int, N> to represent the size when creating/deleting, as well as the index when you're indexing into one).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download