处理不同大小数组的函数
C++: Function to handle different size arrays
我有两个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
}
另一方面,我也更喜欢使用向量:它只是感觉更安全。
相关文章:
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 打印 2D 动态数组 c++ 函数
- C++数组函数
- 在数组函数指针中调用void
- 数组函数似乎没有找到最大值
- 使用数组函数和循环求解伪元编码|C
- 在头文件中的函数原型中获取指针数组:函数声明为 void
- 数组函数错误输出
- 读取文件,然后创建数组函数C++
- 指针数组函数参数-奇怪的行为
- 二维数组 - 函数
- "return"没有从数组函数返回正确的值
- 数组函数问题
- 数组函数的大小返回 int 的大小而不是数组
- 从数组函数中删除元素
- 如何从C++中最好地调用具有C99风格数组函数签名的函数
- 追加/打印/插入数组c++函数问题
- 如何将数组函数转换为指针函数
- 多维数组函数输出垃圾
- C++:数组函数的递归最大值