在 C++ 中实现 1D 数组中的 2D 数组坐标
Implement 2d array coordinates in 1d array in C++
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];
}
}
}
}
假设src
和dst
是大小为 n_rows*n_cols
的不同一维向量......
相关文章:
- 2D数组来自文本输入,中间有空格
- 如何使用用户输入在C++中正确填充2D数组
- 如何在C++中检查2D数组中负值的输入验证
- 当我在main中声明了我的2d数组时,为什么我的程序会退出
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 如何在C++函数中声明静态 2D 数组?
- 如何声明一个可以在整个程序中使用的全局 2d 3d 4d .. 数组(堆版本)变量?
- 我已经阅读了很多关于 2d 数组的信息,但我在作业中使用它时遇到了麻烦
- 使用矢量将文本文件中的输入存储到 2D 数组中
- 获取 2D 数组 c++ 中的所有数字对
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 如何在构造函数中使用初始值设定项设置具有相同值的 2d 数组?
- 在 Python 和 c++ 2d 数组初始化之间.这是怎麽?为什么呢?
- 如何打印 2D 字符数组C++
- 如何将数组 2d 作为参数从函数传递并返回数组 2d 此函数
- 数组 2D 多个值
- 创建数组数组 (2D),而无需在 Java 中初始化内部数组
- 如何在C++中将文本文件传输到数组2D
- 从同一类的另一个方法调用数组2D-C++
- 获取地址在数组2d中的位置