Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- #include <stdexcept>
- #include <vector>
- using namespace std;
- class Matrix {
- public:
- Matrix() {
- }
- Matrix(const int& num_rows, const int& num_cols) {
- if (num_rows < 0 || num_cols < 0) {
- throw out_of_range("");
- }
- Reset(num_rows, num_cols);
- }
- void Reset(const int& num_rows, const int& num_cols) {
- if (num_rows < 0 || num_cols < 0) {
- throw out_of_range("");
- }
- matrix.assign(num_rows, vector<int>(num_cols));
- }
- int GetNumRows() const {
- return matrix.size();
- }
- int GetNumColumns() const {
- return matrix[0].size();
- }
- int At(const int& row, const int& col) const {
- if (row < 0 || col < 0 || row > GetNumRows() || col > GetNumColumns()) {
- throw out_of_range("");
- }
- return matrix[row][col];
- }
- int& At(const int& row, const int& col) {
- if (row < 0 || col < 0 || row > GetNumRows() || col > GetNumColumns()) {
- throw out_of_range("");
- }
- return matrix[row][col];
- }
- private:
- vector <vector<int> > matrix;
- };
- istream& operator>>(istream& stream, Matrix& matrix) {
- int rows, cols;
- stream >> rows >> cols;
- if (rows < 0 || cols < 0) {
- throw out_of_range("");
- }
- matrix.Reset(rows, cols);
- for (int r = 0; r < rows; ++r) {
- for (int c = 0; c < cols; ++c) {
- stream >> matrix.At(r, c);
- }
- }
- return stream;
- }
- ostream& operator<<(ostream& stream, const Matrix& matrix) {
- const int rows = matrix.GetNumRows(), cols = matrix.GetNumColumns();
- stream << rows << ' ' << cols << endl;
- for (int r = 0; r < rows; ++r) {
- for (int c = 0; c < cols; ++c) {
- stream << matrix.At(r, c) << ' ';
- }
- stream << endl;
- }
- return stream;
- }
- Matrix operator+(const Matrix& lhs, const Matrix& rhs) {
- if (lhs.GetNumRows() != rhs.GetNumRows() || lhs.GetNumColumns() != rhs.GetNumColumns()) {
- throw invalid_argument("");
- }
- const int rows = lhs.GetNumRows(), cols = lhs.GetNumColumns();
- Matrix result(rows, cols);
- for (int r = 0; r < rows; ++r) {
- for (int c = 0; c < cols; ++c) {
- result.At(r, c) = lhs.At(r, c) + rhs.At(r, c);
- }
- }
- return result;
- }
- bool operator==(const Matrix& lhs, const Matrix rhs) {
- if ((lhs.GetNumRows() == 0 || lhs.GetNumColumns() == 0) && (rhs.GetNumRows() == 0 || rhs.GetNumColumns() == 0)) {
- return true;
- } else if (lhs.GetNumRows() != rhs.GetNumRows() || lhs.GetNumColumns() != rhs.GetNumColumns()) {
- return false;
- } else {
- const int rows = lhs.GetNumRows(), cols = lhs.GetNumColumns();
- for (int r = 0; r < rows; ++r) {
- for (int c = 0; c < cols; ++c) {
- if (lhs.At(r, c) != rhs.At(r, c)) {
- return false;
- }
- }
- }
- }
- return true;
- }
- int main() {
- Matrix one;
- Matrix two;
- cin >> one >> two;
- cout << one + two << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement