此功能已被问过几次,但我对特定情况感兴趣。是否可以通过附加参数定义传递的数组大小?
举个例子,假设我想要一个打印二维数组的函数。但是,我的数组可能每次都没有相同的维度。如果我可以有额外的参数来定义该数组的大小,那将是理想的。我知道我可以根据需要轻松地在此处将 n
切换为数字,但是如果我有更复杂的函数和单独的头文件,每次不同大小时去编辑头文件似乎很愚蠢数组出现了。以下结果导致 error: use of parameter 'n' outside function body...
我理解但想找到一些解决方法。我也尝试过 g++ -std=c++11
但仍然是同样的错误。
#include <iostream>
using namespace std;
void printArray(int n, int A[][n], int m) {
for(int i=0; i < m; i++){
for(int j=0; j<n; j++) {
cout << A[i][j] << " ";
}
cout << endl;
}
}
int main() {
int A[][3] = {
{1,2,3},
{4,5,6},
{7,8,9},
{10,11,12}
};
printArray(3, A, 4);
return 0;
}
据推测,这可以通过 C99 来完成并且在 this question 中也提到了但我不知道如何使用 C++。
最佳答案
这个有效:
template<size_t N, size_t M>
void printArray( int(&arr)[M][N] ) {
for(int i=0; i < M; i++){
for(int j=0; j < N; j++) {
std::cout << A[i][j] << " ";
}
std::cout << std::endl;
}
}
如果你愿意把代码放在头文件中。作为奖励,它会为您推导出 N
和 M
。
关于C++ 传递由参数确定的动态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26723463/