温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c++ - How to convert an M-dimensional array to an N-dimensional array?
algorithm arrays c++ multidimensional-array templates

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

发布于 2020-03-28 23:23:20

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

让我尝试将其形式化:

输入:

  1. M维容器A

  2. 尺寸D容器(尺寸)

  3. 目标尺寸 N

输出:

如果是,N > 0则返回B内容与A顺序相同的N维容器否则返回错误代码。

注意:

您可以为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:

要在容器的尺寸大小(分辨率)之间A[A0][A1]...[A(M-1)]以及X[A0*A1*...*A(M-1)]哪里A0,A1,...A(M-1)进行转换,只需执行以下操作:

// 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);

其中a0,a1,...a(M-1)x是数组中的索引。

实际上,您实际上不需要将MD数组转换为1D,然后又回到ND,足以将索引转换为:

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)

否则您将无法访问数组,因为其中的数据A将不适合B

如果您具有动态尺寸,则可以使用:

最新帖子

最新文章