【发布时间】:2021-01-11 21:32:18
【问题描述】:
我正在努力将可变大小的二维数组作为参数传递给函数。我已经在网上搜索了一段时间,但没有找到解决方案。在正手创建两个不同大小的数组时,我的代码有效,但是当我使用 for 循环执行此操作时,这不再有效。对于第二个任务,我确实对相同的函数使用相同的变量。我认为看代码时问题变得一清二楚:
#include <iostream>
using namespace std;
template <typename test>
void func(test& array){
cout << "it worked." << endl;
}
int main()
{
//commented section works
//double a1[10][10]; // create 2 differently sized arrays
//double a2[5][5];
//func(a1); //execute the function for those 2 differently sized arrays
//func(a2);
//uncommented section does not work:
for(int i; i<2; ++i){
const int size = 5*(i+1); // variable size
double a[size][size]; // creating an array with a changing size
func(a); // executing the function that is supposed to work
}
return 0;
}
错误信息是:
test.cpp:14:6: 注意:模板参数推导/替换失败:
test.cpp:30:9: 注意:可变大小的数组类型‘double [size][size]’不是>一个有效的模板参数
如何使代码中未注释的部分正常工作?意思是如何在此迭代中将变量二维数组传递给函数。
【问题讨论】:
-
double a[size][size];不是合法的 C++,因为size不是编译时间常数。在底层使用一维向量创建一个矩阵类,并传递该类的一个对象。 -
如果您使用 gcc,请使用
-pedantic-errors进行编译,这样会提示您使用可变长度数组时出错。 -
vector
> 例如 -
Example matrix class 基于一维
vector,这通常比vector<vector<T>>方法快得多,因为使用的存储保存在一个易于缓存的块中。 -
这需要在运行时实例化模板,这是不可能的。
标签: c++ arrays templates multidimensional-array variable-length-array