C ++传送动态数组通过参数确定 [英] C++ Passing Dynamic Array Determined by Parameter
问题描述
此功能已被要求在这里几次,但我有兴趣在特定情况下。是否有可能有数组的大小通过了一个额外的参数定义的?
This function has been asked a few times on here but I am interested in a particular case. Is it possible to have the size of the array passed defined by an additional argument?
作为一个例子,比方说我想要一个功能打印二维数组。然而,我的阵列可以不具有相同的尺寸每一次。这将是理想的,如果我能有额外的参数定义数组的大小。我知道我可以很容易地切换出 N
对于一些在这里作为必要的,但如果我有更复杂的功能,独立的头文件似乎傻去和编辑页眉文件每一个不同大小的数组到来的时间。在的结果如下错误:使用参数的'N'外面的函数体...
这我理解,但想找到一些解决办法。我还与 G ++ -std =试图C ++ 11
,但仍是同样的错误。
As an example, let's say I want a function to print a 2D array. However, I the array may not have the same dimensions every time. It would be ideal if I could have additional arguments define the size of that array. I am aware that I could easily switch out the n
for a number here as needed but if I have more complex functions with separate header files it seems silly to go and edit the header files every time a different size array comes along. The following results in error: use of parameter 'n' outside function body...
which I understand but would like to find some workaround. I also tried with g++ -std=c++11
but still the same error.
#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 的完成,也提到<一href=\"http://stackoverflow.com/questions/4434395/c-passing-dynamically-sized-2d-array-to-function\">this问题但我不能用C ++弄清楚如何。
Supposedly, this can be done with C99 and also mentioned in this question but I cannot figure out how with 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;
}
}
如果你愿意把code头文件中。作为奖励,它演绎 N
和 M
为您服务。
if you are willing to put the code in a header file. As a bonus, it deduces N
and M
for you.
这篇关于C ++传送动态数组通过参数确定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!