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)
首先,我认为你应该创建一个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)
编辑(经过相当长的时间):
或者,我建议使用vector或array:
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)