如何将 2D 数组发送到函数?

How to send a 2D array to a function?

本文关键字:函数 数组 2D      更新时间:2023-10-16

我正在尝试将用户输入的维度的二维矩阵传递给函数,例如arrayTest[r][c]。我已经完成了研究,但找不到有效的答案。如果这很重要,我正在Windows上使用代码块。

我的代码:

#include <iostream>
using namespace std;
int r, c;
template <size_t r, size_t c>
void printMatrix(double (&matrix)[r][c])
{
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
cout<<matrix[i][j]<<" ";
}
cout<<endl;
}
}
int main()
{
r = 1;
c = 1;
double matrix[r][c] = { { } };
printMatrix(matrix);
return 0;
}

我目前收到错误:调用打印矩阵没有匹配函数。

,尺寸由用户输入

double matrix[r][c]

数组变量的大小必须在编译时知道,因此用户不能输入。

但是,您可以动态分配数组。动态内存管理很难正确进行,最好将其抽象到容器对象中。

标准库中已经存在动态数组容器的实现:std::vector。向量元素的类型是模板参数,因此您可以使用向量向量来表示数组数组,即 2D 数组。

@user0042是正确的。 最好的方法是使用向量或其他容器,这样就不需要您创建的模板。

using namespace std;
typedef std::vector<std::vector<double>> Double2D;
void printMatrix(Double2D& matrix)
{
for(int i=0;i<matrix.size();i++)
{
for(int j=0;j<matrix[i].size();j++)
{
cout<<matrix[i][j]<<" ";
}
cout<<endl;
}
}
int main()
{
Double2D matrix = { { } }; // fill the matrix here. depending on the compiler you use, you have to use different methods
printMatrix(matrix);
return 0;
}

在C++中,你应该使用std::vector而不是C 样式的数组。顺便说一下,对于您当前的问题,您可以访问此处将二维数组传递给函数。希望对您有所帮助。此外,在将(&matrix)[r][c]变量传递给函数printMatrix()之前,还需要输入变量rc的值。