【发布时间】:2020-07-25 07:14:08
【问题描述】:
我目前正在尝试制作一个程序,该程序将生成一个要导出到游戏的迷宫。该程序将接受用户输入来设置迷宫的一些属性。我希望其中一个选项是迷宫只有二维(一层)或三层(两层或更多层)。为此,我在 Maze 类中动态分配一个数组,如下所示:
在 Maze.hpp 中:
class Maze {
private:
unsigned int width_, length_, height_;
Cell*** matrix = nullptr;
};
在 Maze.cpp 中:
Maze::Maze() { // Default constructor
width_ = 20;
length_ = 20;
height_ = 0;
matrix = new Cell**[width_];
for (unsigned int x {}; x < width_; ++x) {
matrix[x] = new Cell*[length_];
for (unsigned int y {}; y < length_; ++y) {
matrix[x][y] = new Cell(x, y);
}
}
}
Maze::Maze(int width, int length) { // 2D maze constructor
width_ = width;
length_ = length;
height_ = 0;
matrix = new Cell**[width_];
for (unsigned int x {}; x < width_; ++x) {
matrix[x] = new Cell*[length_];
for (unsigned int y {}; y < length_; ++y) {
matrix[x][y] = new Cell(x, y);
}
}
}
Maze::Maze(int width, int length, int height) { // 3D maze constructor
width_ = width;
length_ = length;
height_ = height;
matrix = new Cell**[width_];
for (unsigned int x {}; x < width_; ++x) {
matrix[x] = new Cell*[length_];
for (unsigned int y {}; y < length_; ++y) {
matrix[x][y] = new Cell[height];
for (unsigned int z {}; z < height_; ++z) {
matrix[x][y][z] = Cell(x, y, z);
}
}
}
}
但是正如你所看到的,如果我使用二维,我最终会得到一个指向迷宫中每个单独单元格的指针,同时,对于三个维度,我最终会得到一个单元格对象。如果在这两种情况下我都可以拥有一个单元格对象,我更愿意,但我不知道如何实现。
有没有办法做到这一点?还是这是我唯一的选择?
按照要求,这里是 Cell 的声明:
细胞.hpp:
class Cell {
private:
unsigned int xPos_, yPos_, zPos_;
public:
Cell(unsigned int xPos, unsigned int yPos);
Cell(unsigned int xPos, unsigned int yPos, unsigned int zPos);
Cell();
};
Cell.cpp:
Cell::Cell(unsigned int xPos, unsigned int yPos) {
xPos_ = xPos;
yPos_ = yPos;
}
Cell::Cell(unsigned int xPos, unsigned int yPos, unsigned int zPos) {
xPos_ = xPos;
yPos_ = yPos;
zPos_ = zPos;
}
【问题讨论】:
-
使用
std::vector或std::array。 2D 迷宫不就是只有一个 2D 入口的 3D 迷宫吗?这会稍微简化问题 -
See this 如果您必须使用三重指针而不是方便的
std::vector。 -
根据您的描述,二维数组将只是一个在第三维中只有一个值的 3D 数组。您应该始终创建一个 3D 数组,但在第 3 维轴上只有一个值。哦,你应该打开你的 C++ 书到解释如何使用
std::vector的章节,阅读它,然后去掉显示代码中的所有new和delete语句。它们的唯一用途是滋生虫子。 -
@SamVarshavchik 我知道如何使用
std::vector,但我记得有人告诉我不要将向量用于多维数组,因为这会产生很多问题。 -
你还记得那些“很多问题”是什么吗?将向量用于多维数组并不会自动出错。在某些情况下,它们可能不是最理想的,但总的来说,除非您准确了解它们的根本原因,否则您不能将这些笼统的概括视为理所当然。
标签: c++ arrays multidimensional-array dynamic-memory-allocation dynamic-arrays