简体   繁体   中英

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 eg 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

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM