且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将矩阵的索引映射到一维数组 (C++)?

更新时间:2022-06-27 01:06:05

大多数语言存储多维数组的方式是进行如下转换:

The way most languages store multi-dimensional arrays is by doing a conversion like the following:

如果 matrix 的大小为 n(行)乘 m(列),并且我们使用的是行优先顺序"(我们首先沿行数)然后:

If matrix has size, n (rows) by m (columns), and we're using "row-major ordering" (where we count along the rows first) then:

matrix[ i ][ j ] = array[ i*m + j ].

这里 i 从 0 到 (n-1) 和 j 从 0 到 (m-1).

Here i goes from 0 to (n-1) and j from 0 to (m-1).

所以它就像一个以m"为基数的数字系统.请注意,最后一个维度的大小(此处为行数)无关紧要.

So it's just like a number system of base 'm'. Note that the size of the last dimension (here the number of rows) doesn't matter.

为了概念上的理解,请考虑一个 (3x5) 矩阵,其中 'i' 为行号,'j' 为列号.如果您从 i,j = (0,0) --> 开始编号0.对于'row-major' 排序(像这样),布局看起来像:

For a conceptual understanding, think of a (3x5) matrix with 'i' as the row number, and 'j' as the column number. If you start numbering from i,j = (0,0) --> 0. For 'row-major' ordering (like this), the layout looks like:

           |-------- 5 ---------|
  Row      ______________________   _ _
   0      |0    1    2    3    4 |   |
   1      |5    6    7    8    9 |   3
   2      |10   11   12   13   14|  _|_
          |______________________|
Column     0    1    2    3    4 

当您沿行移动(即增加列数)时,您只是开始计数,因此数组索引为 0,1,2....当您到达第二行时,您已经有 5 条目,因此您从索引 1*5 + 0,1,2... 开始.在第三行,您已经有 2*5 条目,因此索引为 2*5 + 0,1,2....

As you move along the row (i.e. increase the column number), you just start counting up, so the Array indices are 0,1,2.... When you get to the second row, you already have 5 entries, so you start with indices 1*5 + 0,1,2.... On the third row, you have 2*5 entries already, thus the indices are 2*5 + 0,1,2....

对于更高维度,这个想法可以概括,即对于 3D matrix L by N by M:

For higher dimension, this idea generalizes, i.e. for a 3D matrix L by N by M:

matrix[ i ][ j ][ k ] = array[ i*(N*M) + j*M + k ]

等等.

对于一个非常好的解释,请参阅:http://www.cplusplus.com/doc/tutorial/arrays/; 或更多技术方面的信息:http://en.wikipedia.org/wiki/Row-major_order

For a really good explanation, see: http://www.cplusplus.com/doc/tutorial/arrays/; or for some more technical aspects: http://en.wikipedia.org/wiki/Row-major_order