algorithm arrays c++ multidimensional-array templates

# c++ - 如何将M维数组转换为N维数组？

`arr2D[i][j]`启发`arr1D[i * k + j]`，我想知道一种可以更改任何数组尺寸的算法。

1. `M`维容器`A`

2. 尺寸`D`容器（尺寸）

3. 目标尺寸 `N`

I would understand a C++ or C code better than an algorithm or a code in some other language. But you may help my curiosity in any language as long as it is comprehensible in English :P

Edit:

I don't need any fully working code. I'm just asking for ways to approach this problem. Thanks in advance for any good ideas.

Ardent Coder

149
Spektre 2020-01-31 23:40

So you just want to reformat your matrices while no data is changed. As I hinted in my comment the simplest is to use 1D array mid step for converting from M to N dimensions.

The other answers here are on the same track but are lacking the whole math ... they have just examples up to some small dimension without universal equation so here it is:

``````// M-D -> 1D
x = a0
+a1*A0
+a2*A0*A1
...
+a(M-1)*A0*A1*...*A(M-2);

// 1D -> M-D
q=x;
a0 = q%A0; q/=A0;
a1 = q%A1; q/=A1;
a2 = q%A2; q/=A2;
...
a(M-1) = q%A(M-1); q/=A(M-1);
``````

``````for (a0=0;a0<A0;a0++)
for (a1=0;a1<A1;a1++)
...
for (a(M-1)=0;a(M-1)<A(M-1);a(M-1)++)
{
// M-D -> 1D
x = a0
+a1*A0
+a2*A0*A1
...
+a(M-1)*A0*A1*...*A(M-2);
// 1D -> N-D
q=x;
b0 = q%B0; q/=B0;
b1 = q%B1; q/=B1;
b2 = q%B2; q/=B2;
...
b(N-1) = q%B(N-1); q/=B(N-1);
// copy A -> B
B[b0][b1]...[b(N-1)] = A[A0][A1]...[A(M-1)];
}
``````

``````A0*A1*...*A(M-1) <= B0*B1*...*B(N-1)
``````