简体   繁体   English

将二维数组传递给 function 并用数字填充

[英]Passing 2D array into function and filling it with numbers

I'm trying to do task in C++.我正在尝试在 C++ 中执行任务。 I need create this function:我需要创建这个 function:

void fillArray(std::array<std::array<int, maxColumns>, maxRows> array, size_t rows, size_t columns) {

}

Right now my example code looks like this:现在我的示例代码如下所示:

#include <iostream>
#include <array>
constexpr int maxColumns = 42;
constexpr int maxRows = 334;

void fillArray(std::array<std::array<int, maxColumns>, maxRows> array, size_t rows, size_t columns) {

}


int main()
{
    
}

I need to fill the array with numbers from 1 to rows*columns starting from [0][0] and diagonally.我需要用从 [0][0] 和对角线开始的 1 到 rows*columns 的数字填充数组。 How to declare and initialize the function with array in this example and then fill it diagonally?在本例中如何用数组声明和初始化 function 然后对角填充? Any help would be greatly appreciated!任何帮助将不胜感激!

It should be它应该是

template <std::size_t maxColumns, std::size_t maxRows>
void fillArray(std::array<std::array<int, maxColumns>, maxRows>& array) {
// ...
}

Demo演示

Let's suppose you use a simple one-dimensional valarray (or array if you insist) of the size width * height wrapped in a class:假设您使用一个简单的一维 valarray(或数组,如果您坚持的话),大小宽度 * 高度包装在 class 中:

class Matrix
{
private:
    std::valarray<int> _data;
    int _width, _height;

public:
    Matrix(int width, int height) : _width(width), _height(height), _data(width * height)
    {
    }
}

Then you can add a member function that maps x, y coordinates to an item reference:然后您可以添加一个成员 function 将 x、y 坐标映射到项目引用:

int& item(int x, int y) { return _data[x + _width * y]; }

... and another one for filling it diagonally like this: ...还有一个像这样对角填充它:

void fillDiagonally(int value = 0, int step = 1)
{
    for (int i = 0; i < _height + _width; ++i) {
        // calculate starting coordinates (along left edge and then bottom edge)
        int row = i < _height ? i : _height - 1;
        int col = i < _height ? 0 : i - _height + 1;
        // move diagonally up and right until you reach margins, while filling-in values
        for (int j = 0; j < _width - col && j <= row; ++j) {
            item(col + j, row - j) = value;
            value += step;
        }
    }
}

and use it like this:并像这样使用它:

int main()
{
    Matrix m(8, 5);
    m.fillDiagonally(1);
}

This way, you don't need to pass the array as an argument, because it's a part of the class.这样,您不需要将数组作为参数传递,因为它是 class 的一部分。 Otherwise you would have to pass it by reference, like you were suggested above.否则,您将不得不通过引用传递它,就像上面建议的那样。

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

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