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

How to map the indexes of a matrix to a 1-dimensional array (C++)?

本文关键字:一维数组 c++ 映射 索引      更新时间:2023-10-16

我有一个8x8的矩阵,像这样:

char matrix[8][8];

同样,我有一个64个元素的数组,像这样:

char array[64];

然后我将矩阵绘制为表格,并用数字填充单元格,每个数字从左到右,从上到下递增。

如果我在矩阵中有索引3(列)和4(行),我知道它对应于数组中位置35的元素,正如我所绘制的表中所看到的那样。我相信有某种公式可以将矩阵的2个索引转换为数组的单个索引,但我不知道它是什么。

任何想法?

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

如果matrix的大小为n(行)× m(列),并且我们使用"行为主排序";(先按行数计算)然后:

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

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

它就像一个以m为底的数制。注意,最后一个维度的大小(这里是行数)无关紧要。


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

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

对于高维,这个思想推广,即对于3D matrix L × N × 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

对于行主排序,我认为matrix[ i ][ j ] = array[ i*n + j ]语句是错误的。

偏移量应为offset = (row * NUMCOLS) + column

你的语句结果是row * NUMROWS + column,这是错误的。

您提供的链接给出了正确的解释

像这样?

//columns = amount of columns, x = column, y = row
var calculateIndex = function(columns, x, y){
    return y * columns + x;
};

下面的示例将索引转换回x和y坐标。

//i = index, x = amount of columns, y = amount of rows
var calculateCoordinates = function(index, columns, rows){
    //for each row
    for(var i=0; i<rows; i++){
        //check if the index parameter is in the row
        if(index < (columns * i) + columns && index >= columns * i){
            //return x, y
            return [index - columns * i, i];
        }
    }
    return null;
};