迷宫游戏输入到2D矢量

时间:2014-04-29 22:45:53

标签: c++ vector maze

我正在尝试创建一个从文件导入的迷宫,然后放入一个包含bool矢量的矢量。

我的问题是我从文件中获取了信息,但我不确定如何将其处理为2D矢量。在迷宫中,任何具有“+”的坐标都是路径,而其他任何坐标(空白等)都是墙。起点和终点位置是Location个对象,但我还没编码。

vector<vector<bool> > mazeSpec;
string buffer; //holds lines while they are read in
int length; //holds length of each line/# of columns
Location start, finish;

ifstream mazeFile("maze.txt");
if (!mazeFile) {
    cerr << "Unable to open file\n";
    exit(1);
}

getline(mazeFile, buffer); // read in first line
cout << buffer << endl; //output first line
length = buffer.length(); //length now set so can be compared

while (getline(mazeFile, buffer)) {
    bool path = (buffer == "*");
    cout << buffer << endl;
}

1 个答案:

答案 0 :(得分:0)

你应该用char填充它。 对于文件中的每一行,在mazeSpec中添加一行:

mazeSpec.resize(mazeSpec.size() + 1);

对于您阅读的每个字符,请在您正在处理的mazeSpec行添加一列:

mazeSpec[i].push_back(buffer[j] == '*');

你会得到这样的东西:

int i, j;
vector<vector<bool> > mazeSpec;
string buffer; //holds lines while they are read in
int length; //holds length of each line/# of columns
Location start, finish;

ifstream mazeFile("maze.txt");
if (!mazeFile) {
    cerr << "Unable to open file\n";
    exit(1);
}

getline(mazeFile, buffer); // read in first line
cout << buffer << endl; //output first line
length = buffer.length(); //length now set so can be compared

mazeSpec.resize(1);
for(j = 0; j < buffer.length(); j++) {
    mazeSpec[0].push_back(buffer[j] == '*');  // or perhaps '+'
}

i = 1;
while (!mazeFile.eof()) {   // read in maze til eof
    getline(mazeFile, buffer);

    mazeSpec.resize(mazeSpec.size() + 1);
    for(j = 0; j < buffer.length(); j++) {
        mazeSpec[i].push_back(buffer[j] == '*');  // or perhaps '+'
    }

     cout << buffer << endl;
     i++;
}