#include #include #include #include using namespace std; class Matrix { int _num_rows; int _num_cols; std::vector> _matrix; public: Matrix(): _num_rows(0), _num_cols(0) {} Matrix(int num_rows, int num_cols) { Reset(num_rows, num_cols); } void Reset(int num_rows, int num_cols) { if (num_rows < 0 || num_cols < 0) throw std::out_of_range("out_of_range"); _num_rows = num_rows; _num_cols = num_cols; _matrix.resize(num_rows); for (auto &column : _matrix) { column.resize(num_cols); for (auto &elem : column) { elem = 0; } } } int At(int num_rows, int num_cols) const { if (num_rows < 0 || num_cols < 0 || num_rows >= _num_rows || num_cols >= _num_cols) { throw std::out_of_range(""); } return _matrix[num_rows][num_cols]; } int& At(int num_rows, int num_cols) { if (num_rows < 0 || num_cols < 0 || num_rows >= _num_rows || num_cols >= _num_cols) { throw std::out_of_range(""); } return _matrix[num_rows][num_cols]; } int GetNumRows() const { return _num_rows; } int GetNumColumns() const { return _num_cols; } friend std::istream& operator >> (std::istream &file, Matrix &matrix) { int num_rows, num_cols; file >> num_rows >> num_cols; matrix.Reset(num_rows, num_cols); for (int row = 0; row < num_rows; row++) { for (int col = 0; col < num_cols; col++) { int value; file >> value; matrix.At(row, col) = value; } } return file; } }; bool operator == (Matrix const &first, Matrix const &second) { if (first.GetNumRows() != second.GetNumRows()) return false; if (first.GetNumColumns() != second.GetNumColumns()) return false; for (int row = 0; row < first.GetNumRows(); row++) { for (int col = 0; col < first.GetNumColumns(); col++) { if (first.At(row, col) != second.At(row, col)) return false; } } return true; } Matrix operator + (Matrix const &first, Matrix const &second) { if (first.GetNumRows() != second.GetNumRows()) throw std::invalid_argument(""); if (first.GetNumColumns() != second.GetNumColumns()) throw std::invalid_argument(""); Matrix result(first.GetNumRows(), first.GetNumColumns()); for (int row = 0; row < first.GetNumRows(); row++) { for (int col = 0; col < first.GetNumColumns(); col++) { result.At(row, col) = first.At(row, col) + second.At(row, col); } } return result; } std::ostream& operator << (std::ostream &file, Matrix const &matrix) { file << matrix.GetNumRows() << " " << matrix.GetNumColumns() << std::endl; for (int row = 0; row < matrix.GetNumRows(); row++) { for (int col = 0; col < matrix.GetNumColumns(); col++) { file << matrix.At(row, col); if ((col - 1) != matrix.GetNumColumns()) file << " "; } file << std::endl; } return file; }