在 C++ 中实现 1D 数组中的 2D 数组坐标

Implement 2d array coordinates in 1d array in C++

本文关键字:数组 2D 坐标 1D C++ 实现      更新时间:2023-10-16

for 循环中的代码用于 2d 数组中的 x 和 y(j 和 i("坐标"。如何在一维数组中实现此邻居/索引查找?我想我可以在前四个方程中实现它。但是我对如何实现左上等感到困惑。

for(int i=0; i<cols*rows; i++){
        //Counts current index's 8 neigbour int values
      int count=0;
      int x = i%cols;
      int y = i/rows;
      //rows y i
      //cols x j
      count+= [grid][i][(j-1+cols)%cols] //left
         +[grid][i][(j+1+cols)%cols]    //right
         +[grid][(i-1+rows)%rows][j]    //up
         +[grid][(i+1+rows)%rows][j]    //down
         +[grid][(i-1+rows)%rows][ (j-1+cols)%cols]  //up-left
         +[grid][(i+1+rows)%rows][ (j+1+cols)%cols]  //down-right
         +[grid][(i+1+rows)%rows][ (j-1+cols)%cols]  //down-left
         +[grid][(i-1+rows)%rows][ (j+1+cols)%cols] ;//up-right
}

从一维向量开始:

int rows = 10;
int cols = 10;
vector<int> grid(rows * cols);

您可以通过不同的方式管理它,例如

for(int y = 0; y < rows; y++)
{
    for(int x = 0; x < cols; x++)
    {
        int point = grid[y * rows + x];
    }
}

您可以在任何给定x访问任何点,并在二维平面中y

左上角是:

x = 0;
y = 0;

右下角是

x = cols - 1;
y = rows - 1;

等等。

使用这样的函数

inline int idx(const int i, const int j, const int rows) const
{
    return i * rows + j;
}

将二维索引转换为一维索引。这样,您就不必更改算法。

用法将是grid[idx(i, (j-1+cols)%cols, rows)]

从二维索引模式计算一维坐标的基本公式通常是以下公式之一:

  • row_index * row_length + column_index
  • column_index * column_length + row_index

哪一个适用于您的情况取决于您是希望 2D 数组具有基于行的内存布局还是基于列的内存布局。按照另一个答案中的建议,将此索引的计算分解为一个单独的函数是有意义的。

然后,您只需要以某种方式填写值即可。

您可以这样做,例如:

// iterate big picture
// TODO: make sure to handle the edge cases appropriately
for (int i_row = 1; i_row < n_rows - 1; i_row++) {
    for (int i_col = 1; i_col < n_cols -1; i_col++) {
        // compute values
        dst[i_row*n_cols+i_col] = 0;
        for (int r = i_row-1; r < i_row+2; r++) {
            for (int c = i_col-1; c < i_col+2; c++) {
                dst[i_row*n_cols+i_col] += src[r*n_cols + c];
            }
        }
    }
}

假设srcdst是大小为 n_rows*n_cols 的不同一维向量......