如何在所有大小的情况下都能做到这一点(c++初学者文件输入)
How to make this work when for all sizes (c++ beginner file input)
我正在处理一个项目,该项目从文本文件中读取输入并将其输入到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>());
并不是说现在根本不需要row
和column
变量。
转换为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);
}
}
相关文章:
- 这是什么类型的C++语法,我应该采取什么步骤来理解这一点
- 我无法理解这一点,有人可以帮我解释一下吗?
- 结构本身就包含在内.如何理解这一点?
- 只需要知道我在c ++中打印模式的方式是否有效,或者有另一种方法可以有效地做到这一点
- 我可以直接为指针分配地址吗?如果是,如何做到这一点
- 请证明这一点的合理性 C++.
- 为什么要按值传递string_view?为什么Visual Studio不能优化这一点?
- [expr.unary.op]/9 似乎暗示"运算符!()' 不能应用于下面的类型 A.但编译器不同意这一点
- 为什么我有一个无限循环,我如何以不同的方式做到这一点
- 我想使用 CMake 生成和编译 Visual Studio projet,我需要从构建中排除单元测试文件。有没有办法做到这一点?
- 所有版本的 GCC 都与默认成员初始值设定项作斗争,该初始值设定项捕获了这一点,并结合了继承的构造函数
- 如果有条件使用String.length()的条件,为什么不一致地评估这一点
- 对随机序列进行降采样会降低随机性吗?有没有原理/定理来证明这一点?
- 在C++有没有更好的方法可以做到这一点?检查哪些数字满足条件 [A*B*C = A! + B! + C!]
- 4.5年应该是4年零178年,我如何在C 中做到这一点
- 为什么添加constexpr使VS2013拒绝这一点
- 如何在GTEST中否定匹配者断言或期望这一点
- 循环工作时如何做到这一点?
- 如何做到这一点:Objet.getsObject().setssObject()
- 为什么我在使用 Qt creator 用 C 编译代码时出错,但可以使用 make 文件轻松做到这一点