如何将 2D 数组发送到函数?
How to send a 2D array to a function?
我正在尝试将用户输入的维度的二维矩阵传递给函数,例如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()
之前,还需要输入变量r
和c
的值。
相关文章:
- 第 i 个元素返回 i 的函数数组
- 使用嵌套函数数组是个好主意吗?
- 正确实现类函数数组
- 试图引用已删除函数数组的相等运算符
- 如何在静态函数中使用成员函数数组
- 无法创建函数数组
- 构造函数数组
- 使用开关或定义函数数组 - 更快
- 编写一个函数,该函数将覆盖主函数数组中的值
- 可以像'funs[1]();'一样调用的函数数组
- std::AVX内部函数数组
- 如果数组大小未知,如何将函数数组作为参数传递
- 从函数数组中获取值
- 使用元编程在编译时初始化函数数组
- 将C函数数组转换为C++函数指针数组
- 复制构造函数 [数组] C++
- 添加函数数组并随机选择其中一个
- 指针到私有成员函数数组
- 可以单独声明函数数组的元素
- (c++)将main中的随机值保存到函数数组中