简体   繁体   English

C ++:可变大小的2D数组作为函数的参数

[英]C++: Variable Size 2D array as an argument to a function

I need the simplest way to solve this issue: when i tried to compile the code below, it says you cant use nR outside the body of the function, passing double pointer in declaration of the function does not work, because it did not allow me to cast, : 我需要解决此问题的最简单方法:当我尝试编译以下代码时,它说您不能在函数主体之外使用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;
}

You can do it if you make your function a template: 如果将函数设为模板,则可以执行以下操作:

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;
    }
  }
}

And then in main: 然后在主要:

int main(){
  int requests[2][3] = { { 1, 2, 3} , { 4, 32, 6 } };
  A(requests);
  return 0;
}

C++ (and C) arrays are not resizeable and do not contain size information. C ++(和C)数组不可调整大小,并且不包含大小信息。

To do this you should use std::vector 为此,您应该使用std::vector

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM