[英]How to populate a vector of vector of set from file?
我的 txt 文件中有一个 3x3 矩阵,其中包含一些数字和一些像这样的零
0 0 3
1 0 0
0 2 0
我想把它当作集合向量的向量来读。 在我有零的地方,我想用数字 123 填充那个单元格。比如
1231233
1123123
1232123
我想知道我是否打印正确。
我写了这段代码:
class Matrix {
private:
vector<vector<set<int> > > cell;
public:
Matrix(const string& filename) {
ifstream file("matrix.txt");
if (!file.good()) {
cerr<<"Error";
}
int x;
int y;
for(x=0; x<3; x++) {
for(y=0; y<3; y++) {
for(vector<vector<set<int> > >::iterator it = cell.begin(); it != cell.end(); it++) {
if(file != 0) {
cell[x][y] = file; // Don't think this part of code is good because I get error here
} else {
int z;
for(z = 1; z<4; z++) {
cell[x][y].insert(z);
cout<<cell[x][y]; // Of course I get an error here too.
}
}
}
}
}
}
}
该迭代是否有用? 我没有在任何地方使用“它”,但我认为我必须在一个集合中使用它。
当然有些东西不正确或缺失,但我不明白是什么以及为什么。 我必须使用向量和集合。
我宁愿打印它以了解我是否做得好。
编辑尝试写入文件>> cell[x][y]; 给我这个错误:[错误] 无法将 'std::basic_istream' 左值绑定到 'std::basic_istream&&'。
您已经声明了向量的向量,但它们都是空的; 您无法通过索引访问任何元素。 您可能希望将它们的大小分别调整为3
元素。
如果您知道它们是3x3
,只需使用std::array
:
std::array< std::array<std::set<int>, 3>, 3> cell;
此外, set
没有实现 operator <<
,所以你必须自己做(使用循环):
cell[1][2].insert(7);
cell[1][2].insert(13);
for(auto x: cell[1][2])
std::cout << x;
std::cout << std::endl;
运营商>>
也一样:
int val(0);
std::cin >> val;
cell[1][2].insert(val);
PS 您在Matrix
的构造函数中进行了太多操作。 如果文件"matrix.txt"
不存在怎么办? 还是格式不好? 你有一个无效的 object,所以要使用它你需要实现类似valid()
方法的东西。 最好构建一个空矩阵并以不同的方法加载它,例如load()
。
以下是如何使用向量、加载和打印:
std::vector<std::vector<std::set<int>>> cell(3, std::vector<std::set<int>>(3));
// load from file
int val(0);
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
file >> val;
cell[x][y].insert(val);
}
}
// print
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
for (auto it = cell[x][y].begin(); it != cell[x][y].end(); it++)
std::cout << *it;
}
}
当然,这不会打印任何内容,因为集合是空的。 你可以像我上面那样阅读这些集合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.