C++ 使用列边界导航数组

C++ 使用列边界导航数组,c++,arrays,vector,C++,Arrays,Vector,假设有一个nxn的二维正方形数组,表示为一维数组。让数组为5x5,如下所示,数组中的值不重要 std::vector< int > array { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4 }; 也许可以使用模数(指数%5==0)来确定是否在边缘上。但这并不决定我们可以向左走还是向右走。您可以使用 int row = index / N;

假设有一个nxn的二维正方形数组,表示为一维数组。让数组为5x5,如下所示,数组中的值不重要

std::vector< int > array {
    0, 1, 2, 3, 4,
    5, 6, 7, 8, 9,
    0, 1, 2, 3, 4,
    5, 6, 7, 8, 9,
    0, 1, 2, 3, 4
};
也许可以使用模数(指数%5==0)来确定是否在边缘上。但这并不决定我们可以向左走还是向右走。

您可以使用

int row = index / N;
int col = index % N;
获取行和列索引。例如,第9个条目的行索引9/5=1,列索引9%5=4

计算完
(行,列)
坐标后,您可以确定它是左邻域还是右邻域。当
col==0
时,您没有左邻居;当
col==N-1
时,您没有右邻居。

您的公式

int index = row * num_cols + col;
上升或下降相当于加/减
num\u cols

这是正确的。反之亦然

int row = index / num_cols;
int col = index % num_cols;
(索引%num\u cols)==0
时,您就知道自己处于左侧边缘

(索引%num\u cols)==num\u cols-1
时,您知道自己处于正确的边缘

int row = index / num_cols;
int col = index % num_cols;