[英]C++: Variable Size 2D array as an argument to a function
我需要解决此问题的最简单方法:当我尝试编译以下代码时,它说您不能在函数主体之外使用nR,在函数的声明中传递双指针不起作用,因为它不允许我投放:
A(int nT, int nR, int arr[][nR]){
for(int i = 0; i< nT; i++){
for(int j = 0; j< nR; j++){
cout<< arr[i][j] << endl;}
}
}
int main(){
int requests[2][3] = { { 1, 2, 3} , { 4, 32, 6 } };
A(2,3, requests );
return 0;
}
如果将函数设为模板,则可以执行以下操作:
template<std::size_t N, std::size_t M>
A(int (&arr)[N][M]){
for(int i = 0; i< N; i++){
for(int j = 0; j < M; j++){
cout<< arr[i][j] << endl;
}
}
}
然后在主要:
int main(){
int requests[2][3] = { { 1, 2, 3} , { 4, 32, 6 } };
A(requests);
return 0;
}
C ++(和C)数组不可调整大小,并且不包含大小信息。
为此,您应该使用std::vector
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.