处理不同大小数组的函数

C++: Function to handle different size arrays

本文关键字:数组 函数 小数 处理      更新时间:2023-10-16

我有两个2D数组代表一个迷宫

const char maze1[10][11]const char maze2[20][21]

我试图创建一个函数来处理两个迷宫,像这样:

void solveMaze(maze[][])
{
}

solveMaze(maze1);一样通过迷宫
然而,我必须为数组提供一个大小,这取决于传入的迷宫。没有重载函数或使用函数模板,我怎么能有一个函数来处理两个数组?

c++答案

使用std::vector:

// Initialize the vector with 11 rows of 10 characters
std::vector<std::vector<char> > maze(11, std::vector<char>(10));
void solveMaze(const std::vector<std::vector<char> > &maze) {
    // note that you can access an element as maze[x][y]
}

boost::multi_array稍微更有效(如果允许使用boost)。我觉得应该是这样的:

boost::multi_array<char, 2> maze(boost::extents[10][11]);
void solveMaze(const boost::multi_array<char, 2> &maze) {
    // note that you can access an element as maze[x][y]
}
<标题> C回答

使用指针:

const char maze1[10][11];
void solveMaze(char *maze, size_t x_length, size_t y_length) {
    // note that you can access an element as maze[x + (x_length * y)]
}

Std c++不允许可变大小的数组。Gnu扩展允许这样做。

给定一个gnu编译器,你可以

 void solvemaze(int w, int h, const char maze[h][w])
 {    //solve it...
 }

,

 void solvemaze(int w, int h, const char *maze)
 {    //solve it, bearing in mind:
      //maze[y][x] = maze[(w*y)+x];
 }

其实不用vector也可以求解:

template<size_t N, size_t M>
void foo(char (&maze)[N][M])
{
    // do your stuff here
}

另一方面,我也更喜欢使用向量:它只是感觉更安全。