如何在所有大小的情况下都能做到这一点(c++初学者文件输入)

How to make this work when for all sizes (c++ beginner file input)

本文关键字:这一点 c++ 初学者 输入 文件 情况下      更新时间:2023-10-16

我正在处理一个项目,该项目从文本文件中读取输入并将其输入到2d数组中。如果我想让它适用于所有尺寸,我应该使用向量吗。如果是这样的话,我对2d向量的语法感到困惑。

或者,如果我应该使用动态数组,你能给我建议吗,因为我以前没有处理过它们。//它从文本文件中读取输入,并将每行的每个字插入阵列

ifstream file(argv [1]);
int length = atoi(argv[2]);
int grid [20][20];
int row = 0, column = 0;
string line;
while(getline (file, line)) {
     istringstream stream(line);
     int x;
     column = 0;
     while(stream >> x) {
         grid[row][column] = x;
         column++;
     }
     row++;
}

我的主要困惑是是否使用2d矢量或数组,如果是,如何启动

更改数组的初始声明(和构造)如下:

int grid [20][20];

vector<vector<int>> grid; // Now the size is 0x0

然后将向内部数组(矢量)添加新值从grid[row][column] = x;更改为grid.back().push_back(x);

row++grid.push_back(vector<int>());

并不是说现在根本不需要rowcolumn变量。


转换为std::vector的完整代码使用

ifstream file(argv [1]);
int length = atoi(argv[2]);
vector<vector<int>> grid;
string line;
while(getline (file, line)) {
     istringstream stream(line);
     grid.push_back(vector<int>());
     int x;
     while(stream >> x) {
         grid.back().push_back(x);
     }
}
相关文章: