简体   繁体   English

遍历2D数组(对角线)c ++

[英]looping through a 2D array (diagonal) c++

So I initialized an array as array[8][8] let's suppose that I'm at point (row, column) and for example, it is row 4 column 4 and I want to loop through every diagonal direction (southeast, southwest, northeast, northwest) 因此,我将数组初始化为array [8] [8],让我们假设我在点(行,列)处,例如,它是第4行第4列,并且我想遍历每个对角线方向(东南,西南,东北,西北)

8 * 8阵列

so I wrote 4 different functions to check each direction alone, and here is an example for Northeast 所以我写了4个不同的函数来单独检查每个方向,这是东北的一个示例

for(int i = 0; i < 8; i++)
    for(int j = 0; j < 8; j++)
        if(array[i - 1][j+1] == 'x')
        {
           count = count + 1; 
        }

is there is a way to loop in all diagonal directions at the same time? 有没有一种方法可以同时在所有对角线方向上循环播放? another problem is what about getting out of bounds, like if the point is (7,7), then there will be no value in northeast because it will exceed the array bounds array[6][8], and that is out of array bounds. 另一个问题是如何越界,例如,如果点是(7,7),则东北方向将没有值,因为它将超出数组边界array [6] [8],并且超出数组范围界限。 How can I deal with this problem? 我该如何解决这个问题? or does the compiler return an error when it happens? 还是编译器在发生错误时返回错误?

You can of course check in each direction, eg 您当然可以检查各个方向,例如

for(int i = 0; i < 8; i++) {
    for(int j = 0; j < 8; j++) {
        if (check_north_east(array, i, j))
            ++count;

        if (check_north_west(array, i, j))
            ++count;

        if (check_south_east(array, i, j))
            ++count;

        if (check_south_west(array, i, j))
            ++count;
    }
}

The compiler will happily go beyond the array bounds. 编译器将愉快地超越数组范围。 So you must make sure, the code won't do it, and check yourself 因此,您必须确保代码不会这样做,并检查一下自己

const int NROWS = 8, NCOLS = 8;
bool check_north_east(char array[][NCOLS], int row, int col)
{
    if (row <= 0 || col >= NCOLS - 1)
        return false;

    return array[row - 1][col + 1] == 'x';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM