水平交替填充数组C++

Filling the array horizontally alternately C++

我正在尝试水平交替填充数组,例如:

我的默认 ArrayFill 函数是:

void fillArray(std::array<std::array<int, maxColumns>, maxRows> & array, size_t rows, size_t columns)
{
    if (rows == 0 || rows > maxRows || columns == 0 || columns > maxColumns)
        throw std::invalid_argument("Invalid array size.");
    int value = 1;
    for (size_t row = 0; row < rows; ++row)
        for (size_t column = 0; column < columns; ++column)
            array[row][column] = value++;
}

如何更改水平填充数组的实现?

我尝试了建议的解决方案,结果如下:

-- 最终的 --(完美运行)

您应该遵守两个属性:

  1. 不是从顶部(行=0)开始填充,而是从底部(行=行-1)开始填充
  2. 每行(从下到上)改变列的顺序

所以,最后它看起来像这样:

int value = 1;
int colOrder = 1; // 1 means from left to right, 0 from right to left
for (size_t row = 0; row < rows; ++row) {
    for (size_t column = 0; column < columns; ++column)
        array[rows - 1 - row][colOrder ? column : (columns - 1 - column)] = value++;
    colOrder ^= 1; // change column order
}