【问题标题】:How to send 2 dimensional Matrix with unknown size to a function如何将未知大小的二维矩阵发送到函数
【发布时间】:2017-10-30 19:41:13
【问题描述】:

我正在尝试弄清楚如何将二维矩阵传递给函数

//function to print Matrix
void refl(int n, int board[][])
{
    for(int i=0; i<n; i++)
    {
        for(int j=0; j<n; j++)
        {

            cout << board[i][j]  << "  ";
            }
        cout << endl; //printing the matrix to the screen
    }
}

int main()
{
    int n;
    string refl;
    cin>>n;
    int board[n][n]; //creates a n*n matrix or a 2d array.

        for(int i=0; i<n; i++)    //This loops on the rows.
    {
        for(int j=0; j<n; j++) //This loops on the columns
            cin>>board[i][j];
    refl(n , board);
    }

return 0;
}

它说“n”和“board”没有在函数中声明。

【问题讨论】:

    标签: c++ arrays function matrix multidimensional-array


    【解决方案1】:

    尝试使用 C++ std::vector 或旧的 C malloc+free

    C++

    #include <string>
    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    void reflxx(int n, vector<vector<int>>& board)
    {
        for(int i=0; i<n; i++)
        {
            for(int j=0; j<n; j++)
            {
    
                cout << board[i][j]  << "  ";
                }
            cout << endl; //printing the matrix to the screen
        }
    }
    
    int main()
    {
        int n;
        string refl;
        cin>>n;
        vector<vector<int>> board(n, vector<int>(n));
         //creates a n*n matrix or a 2d array.
    
            for(int i=0; i<n; i++)    //This loops on the rows.
        {
            for(int j=0; j<n; j++) //This loops on the columns
                cin>>board[i][j];
        }
        reflxx(n , board);
    
    return 0;
    }
    

    更多示例请参见http://www.cplusplus.com/reference/vector/vector/resize/

    【讨论】:

    • 我已经尝试了你的方法,现在我得到了这个错误:|29|error: no match for call to '(std::string {aka std::basic_string&lt;char&gt;}) (int&amp;, int [n][n])'| 特别是在这行代码 refl(n , board);
    • 啊,我应该在发布之前尝试编译它,但无法让它工作。通常,如果我们想在运行时创建一个可变大小的动态数组,我们可以使用malloc+freestd::vector
    • 我要求的太多了,但你能告诉我如何使用 std::vector 吗?因为我听说了很多。
    • 感谢 John,感谢您的帮助 ^^ 但是当我运行它时,该函数只打印第一行
    • 您的意思是每次完成一行数据的输入,程序都会打印整个矩阵(这意味着如果 n = 3,程序会打印 3x3 矩阵 3 次)?您只想在输入所有数据后打印?
    猜你喜欢
    • 2019-03-05
    • 1970-01-01
    • 2012-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-11
    • 2023-02-09
    相关资源
    最近更新 更多