How about:
Code:
struct Matrix {
vector<vector<int>> m;
Matrix(size_t rows, size_t cols) : m(rows) {
for (size_t i = 0; i < rows; i++)
m[i].resize(cols);
}
};
And your code is only reading one matrix because there's no loop to read more than one!
Naming issues:
Matrices should be called Matrix since it only holds one.
File should be called file since all other variables start with a lowercase letter. The common style is for user-defined types (like Matrix) to start with an uppercase letter and variables to start lowercase.
itr is misnamed (if it stands for "iterator") since it is not an iterator. That's kind of the point of the new-style for - it allows you to avoid the actual iterators and deal just with the values.
Code:
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
const size_t SIZE = 3;
struct Matrix {
vector<vector<int>> m;
Matrix(size_t rows, size_t cols) : m(rows) {
for (size_t i = 0; i < rows; i++)
m[i].resize(cols);
}
};
ostream& operator<<(ostream& os, const Matrix& mat) {
for (size_t i = 0; i < mat.m.size(); i++) {
for (size_t j = 0; j < mat.m[i].size(); j++)
os << mat.m[i][j] << '\t';
os << '\n';
}
return os;
}
istream& operator>>(istream& is, Matrix& mat) {
for (size_t i = 0; is && i < mat.m.size(); i++)
for (size_t j = 0; is && j < mat.m[i].size(); j++)
is >> mat.m[i][j];
return is;
}
int main() {
vector<Matrix> mats;
ifstream file("matrix_file");
while (file) {
Matrix m(SIZE, SIZE);
file >> m;
if (file)
mats.push_back(move(m));
}
for (auto& mat : mats)
cout << mat << '\n';
}
Note that it would be possible to read an arbitrarily-sized matrix by reading a line at a time, adding a row, reading those numbers (from an sstream) into the new row, and keep going until you encounter a blank line (or eof). So it could read a file like this:
Code:
1 2
3 4
8
1 2 3 4 5 6 7
7 6 5 4 3 2 1