C++: Function to handle different size arrays
I have 2 2D arrays that represent开发者_如何学JAVA a maze
const char maze1[10][11]
and
const char maze2[20][21]
I'm trying to create 1 function to handle both mazes like so:
void solveMaze(maze[][])
{
}
and just pass the maze like solveMaze(maze1);
C++ answer
Use 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]
}
The boost::multi_array
is slightly more efficient (if you're allowed to use boost). I think it goes something like this:
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 answer
Use pointers:
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++ doesn't allow variably sized arrays. Gnu extensions allow this.
given a gnu compiler, you can
void solvemaze(int w, int h, const char maze[h][w])
{ //solve it...
}
otherwise,
void solvemaze(int w, int h, const char *maze)
{ //solve it, bearing in mind:
//maze[y][x] = maze[(w*y)+x];
}
Actually it can be solved without vector:
template<size_t N, size_t M>
void foo(char (&maze)[N][M])
{
// do your stuff here
}
On the other hand, I would also prefer to use vectors: it just feels safer.
精彩评论