C++ 在C+中的一维数组中实现二维数组坐标+;
for循环中的代码用于二维数组中的x和y(j和i)“坐标”。如何在一维数组中实现此邻居/索引查找? 我想我可以为前四个方程实现它。但我不知道如何实现左上角等等C++ 在C+中的一维数组中实现二维数组坐标+;,c++,arrays,C++,Arrays,for循环中的代码用于二维数组中的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
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
}
for(int i=0;i使用如下函数
inline int idx(const int i, const int j, const int rows) const
{
return i * rows + j;
}
将二维索引转换为一维索引。
这样,您就不必更改算法
使用方法是网格[idx(i,(j-1+cols)%cols,rows)]
从一维向量开始:
int rows = 10;
int cols = 10;
vector<int> grid(rows * cols);
右下角是
x = cols - 1;
y = rows - 1;
依此类推。从二维索引模式计算一维坐标的基本公式通常是以下公式之一:
行索引*行长度+列索引
列索引*列长度+行索引
哪一个适用于您的情况取决于您是否想要一个。将此索引的计算分解为一个单独的函数是有意义的
然后,您只需要以某种方式填充这些值
您可以这样做,例如:
// 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];
}
}
}
}
//迭代大画面
//TODO:确保适当处理边缘情况
对于(int i_row=1;i_row
假设src
和dst
是大小不同的1d向量n行*n列
。你的意思是你有一个1d数组,例如int grid[rows*cols]
?你已经计算了x
y
其中的数据应该是grid[i]
是的,我的一维数组的大小是rows*cols。我有一个一维数组,但邻域查找是针对二维数组的。我想知道如何对一维数组执行此等式。你能得到坐标(x,y)吗如果你知道索引i
,那么x=i%cols
和y=i/rows
,你自己已经做到了!相反,如果你知道x
和y
,那么索引就是i=y*rows+x
,如上所示。
x = cols - 1;
y = rows - 1;
// 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];
}
}
}
}