你如何在C++中返回一个二维数组?

Sal*_*ban 3 c++

如何在C++中返回二维数组?

例如,我在java中有以下方法:

public static int[][] getFreeCellList(int[][] grid) {
    // Determine the number of free cells
    int numberOfFreeCells = 0;
    for (int i=0; i<9; i++) 
      for (int j=0; j<9; j++)
        if (grid[i][j] == 0)
          numberOfFreeCells++;

    // Store free cell positions into freeCellList
    int[][] freeCellList = new int[numberOfFreeCells][2];
    int count = 0;
    for (int i=0; i<9; i++)
      for (int j=0; j<9; j++)
        if (grid[i][j] == 0) {
          freeCellList[count][0] = i;
          freeCellList[count++][1] = j;
        }
    return freeCellList;
  }
Run Code Online (Sandbox Code Playgroud)

我试图用C++复制它.通常,我会传入我想要返回的2d数组作为C++中方法的参考参数.

但是,正如您在上面的方法中看到的那样,直到运行时才知道返回的数组的大小.

所以,在这种情况下,我猜我需要实际返回一个二维数组,对吧?

dir*_*tly 5

您可以使用vectorvector为好.

typedef vector<vector<int> > array2d_t;

array2d_t etFreeCellList(array2d_t grid) {
    // ...

    array2d_t freeCellList;

    // Determine the number of free cells
    int numberOfFreeCells = 0;
    for (int i=0; i<9; i++) 
       for (int j=0; j<9; j++)
          if (grid[i][j] == 0) {
      freeCellList[count][0] = i;
      freeCellList[count++][1] = j;
    }
    return freeCellList; 
}
Run Code Online (Sandbox Code Playgroud)