我正在尝试从 20x20 文件中的网格中读取数据。我正在使用字符串 vector 的二维 vector 。
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
#define HEIGHT 20
#define WIDTH 20
typedef vector<vector<string> > stringGrid;
bool readGrid(stringGrid& grid, string filename) {
grid.resize(HEIGHT);
for (int i = 0; i < HEIGHT; i++)
grid[i].resize(WIDTH);
ifstream file;
string line;
file.open(filename.c_str());
if (!file.is_open()) {
return false;
}
for (int i = 0; i < HEIGHT; i++)
{
while (getline(file, line)) {
grid[i].push_back(line);
}
}
return true;
}
void displayGrid(stringGrid grid)
{
for (int row = 0; row < HEIGHT; row++)
{
for (int col = 0; col < WIDTH; col++)
{
cout << grid[col][row];
}
cout << endl;
}
}
int main(){
stringGrid grid;
readGrid(grid, "test.txt");
displayGrid(grid);
return 0;
}
但是,当我运行这段代码时,程序只输出了几个空行。 为什么这段代码不起作用?这个逻辑似乎足够合理。
最佳答案
您可以按照 Kocik 所说的进行操作,或者您可以在代码中使用 vector::reserve
而不是 vector::resize
。然后它应该可以工作。
reserve
只是保留足够的内存以避免在推回项目时重新分配内存。
resize
实际上是通过添加 n 个默认项来调整 vector 的大小。在您的情况下,这些项目是字符串的空 vector ,因此在您随后推回的任何其他项目之前,您将在 vector 中获得其中的 20 个。
Here是关于这两种方法之间差异的更多信息。
关于c++ - 从文件创建二维 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23839669/