c++ - 在具有其他整数成员变量的类中将 2D char 数组声明为 c++ 中的大小
问题描述
我正在使用的类如下所示。我正在解析来自 txt 文件的数据并将其保存为 numRows 和 numCols,并且我希望 2D 字符数组迷宫具有我刚刚解析的那些维度的大小。我怎样才能做到这一点?我在上大学,程序任务要求 numRows、numCols 和 2D char 数组是 Board 类的私有成员。
class Board
{
public:
Board()
{
for (int i = 0; i < numRows; i++)
{
for (int j = 0; j < numCols; j++)
{
maze[i][j] = emptyPos;
}
}
}
Player getPlayer() { return User; }
void parseMazeData(int &rowStartPos, int &colStartPos);
private:
int numRows;
int numCols;
char maze[numRows][numCols];
Player User;
};
解决方案
I suppose you don't know upfront the number of rows and columns, so you need to perform a dynamic allocation. If my assumption is right you need to have already parsed the maze data before doing anything with the array.
So, once you parse those dimensions you can do:
Board() {
//Parse maze data somehow before and then:
maze = new char[nrows*ncols]
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
maze[i][j] = emptyPos;
}
}
}
This of course will require you to clean up this maze array in the destructor of this Board class.
A much nicer solution would be using std::vector, since it provides the cleanup for you. Think of it as a high level array with extra functionalities and safer API. This way, maze would be declared as:
std::vector<std::vector<char>> maze.
With that you would not need to write a destructor yourself and your constructor would be like:
Board() {
//Parse maze data somehow before and then:
maze.size(numRows);
for (int i = 0; i < numRows; i++) {
maze.at(i).size(numCols);
for (int j = 0; j < numCols; j++) {
maze[i][j] = emptyPos;
}
}
}
推荐阅读
- python - 将字符串转换为具有不同格式python的日期时间对象
- elasticsearch - Logstash 到 Elasticsearch 在字段中添加新数据而不是覆盖现有数据?
- android - 我可以将我的物理笔记本电脑的 USB 端口连接到云机吗?我想使用 android studio 测试 android 应用
- javascript - 角度存储检查失败
- flutter - 颤振:提供者在 statefulwidget 中不起作用
- javascript - 使用“getElementById”更改按钮背景
- reactjs - 在 Material UI 中将 className 传递给 themeprovider
- git - 无法从 docker 容器标记 SCM maven 发布插件目标执行
- amazon-web-services - AWS EC2 + Cloudfront - 我可以在没有密钥对的情况下通过 CloudFront 进行 SSH 连接吗?
- vue.js - 在 div v-for (Vuejs) 中添加分页