c++ - 从文件创建二维 vector ?

标签 c++ arrays file vector

我正在尝试从 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/

相关文章:

c++ - 如何将整个结构传递给包含所有元素的函数?

c++ - 并发追加到文件:写入丢失

file - 如何保护文件不被直接下载?

c++ - 空内联函数到底发生了什么?

c++ - 使文件在Windows中可写

c++ - 为什么 lambda 参数的默认参数会触发“-pedantic”GCC 警告?

PHP:如何提取ajax数组响应

php - 将 php 字符串拆分为不同长度的 block

python - 如何使用冒泡排序在 Python 3 中对列表进行排序和子排序

file - 从代码获取 Azure VM 上可用的驱动器