gpt4 book ai didi

c++ - 如何将未知大小的二维矩阵发送给函数

转载 作者:行者123 更新时间:2023-11-28 05:07:45 25 4
gpt4 key购买 nike

我想弄清楚如何将二维矩阵传递给函数

//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++ 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/更多示例。

关于c++ - 如何将未知大小的二维矩阵发送给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44260405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com