如何在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;
}我正在尝试在C++中复制这一点。通常,我会传入希望在C++中作为该方法的引用参数返回的2d数组。
但是,正如您在上面的方法中看到的,返回的数组的大小直到运行时才知道。
所以,在这种情况下,我猜我实际上需要返回一个二维数组,对吧?
发布于 2010-02-27 06:04:10
您也可以使用vector的vector。
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;
}发布于 2010-02-27 06:06:04
内部数组的大小似乎固定为2。因此,可以使用array的向量
static std::vector< array<int, 2> > getFreeCellList(int grid[][9]) {
// 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
std::vector< array<int, 2> > freeCellList(numberOfFreeCells);
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;
}用法是这样的
int x[9][9] = { ... };
std::vector< array<int, 2> > pa = getFreeCellList(x);由于您使用的是std::vector,因此不需要手动管理内存。array在boost中,但您可以快速手动编写类似的类
template<typename E, int N>
struct array {
E &operator[](int I) { return data[I]; }
E data[N];
};数据成员是E类型的N元素的数组。
或者,您可以使用低级2d数组来编写此代码。由于内部维度在代码中是固定的,因此您可以实际分配一个真实的本机2d数组,而不是将复杂的指针1d数组分配给单独的缓冲区:
static identity<int[2]>::type *getFreeCellList(int grid[][9]) {
// 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)[2] = 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;
}现在你可以像这样使用它
int x[9][9] = { ... };
// equivalent: identity<int[2]>::type *pa = ...;
int (*pa)[2] = getFreeCellList(x);
// ...
delete[] pa;请注意使用identity (来自boost或参见下文)来简化语法。否则,您需要编写以下代码
static int (*getFreeCellList(int grid[][9]))[2] {
// ...
}// identity implementation (for working around the evil C++ syntax)
template<typename T>
struct identity { typedef T type; };发布于 2010-02-27 06:00:25
您可以将其放入结构中,然后返回该结构。否则,C++不允许返回数组。您还可以返回指向第一个元素的指针(平面一维数组或完全动态的二维数组)。
https://stackoverflow.com/questions/2345124
复制相似问题