读取矩阵从文本文件到2D整数数组C++

bur*_*gun 2 c++ arrays file matrix

1 3 0 2 4 
0 4 1 3 2 
3 1 4 2 0 
1 4 3 0 2 
3 0 2 4 1 
3 2 4 0 1 
0 2 4 1 3
Run Code Online (Sandbox Code Playgroud)

我在.txt文件中有这样的矩阵.现在,如何int**以最佳方式将此数据读入一种2D数组?我在网上搜索但找不到令人满意的答案.

array_2d = new int*[5];
        for(int i = 0; i < 5; i++)
            array_2d[i] = new int[7];

        ifstream file_h(FILE_NAME_H);

        //what do do here?

        file_h.close();
Run Code Online (Sandbox Code Playgroud)

Moh*_*oun 6

首先,我认为你应该创建一个int*[]7的大小并从1到7循环,同时在循环中初始化一个5的int数组.

在这种情况下,你会这样做:

array_2d = new int*[7];

ifstream file(FILE_NAME_H);

for (unsigned int i = 0; i < 7; i++) {
    array_2d[i] = new int[5];

    for (unsigned int j = 0; j < 5; j++) {
        file >> array_2d[i][j];
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑(经过相当长的时间):
或者,我建议使用vectorarray:

std::array<std::array<int, 5>, 7> data;
std::ifstream file(FILE_NAME_H);

for (int i = 0; i < 7; ++i) {
    for (int j = 0; j < 5; ++j) {
        file >> data[i][j];
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @burakongun要添加Magtheridon的注释,数组应该是结构化的(7 x 5)是因为文件中数组的排序是按行号,然后是每行的整数(这在逻辑上与文件的顺序相匹配)被读入).如果你使用你的原始结构并从i =(0到4)和j =(0到6)循环"file >> array2d [i] [j]",你将无法得到原始数组的正确表示.您将获得{{1,3,0,2,4,0,4},{1,3,2,3,1,4,2},{0,1,4,3,0,2, 3},{0,2,4,1,3,2,4},{0,1,0,2,4,1,3}}这不是你问题中2D数组的有效表示. (2认同)