Загрузка...

Solve a problem in c++

Thread in C/C++ created by Misodzi Dec 19, 2022. 264 views

  1. Misodzi
    Misodzi Topic starter Dec 19, 2022 0 Jun 9, 2019
    Реализуй класс для хранения квадратной матрицы. перезагрузите метод + и -, сгенерируйте и обработайте ошибки
     
  2. brediska
    brediska Jan 6, 2023 Banned 2794 May 30, 2021
    Code
    #include <iostream>
    #include <vector>

    using namespace std;

    class Matrix {
    private:
    int size;
    vector<vector<int>> data;

    public:
    Matrix(int size) : size(size) {
    // Initialize the matrix with all zeros
    data.resize(size);
    for (int i = 0; i < size; i++) {
    data[i].resize(size);
    for (int j = 0; j < size; j++) {
    data[i][j] = 0;
    }
    }
    }

    // Overload the + operator
    Matrix operator+(const Matrix &other) {
    if (size != other.size) {
    throw invalid_argument("Matrices must be of the same size to add them");
    }

    Matrix result(size);
    for (int i = 0; i < size; i++) {
    for (int j = 0; j < size; j++) {
    result.data[i][j] = data[i][j] + other.data[i][j];
    }
    }
    return result;
    }

    // Overload the - operator
    Matrix operator-(const Matrix &other) {
    if (size != other.size) {
    throw invalid_argument("Matrices must be of the same size to subtract them");
    }

    Matrix result(size);
    for (int i = 0; i < size; i++) {
    for (int j = 0; j < size; j++) {
    result.data[i][j] = data[i][j] - other.data[i][j];
    }
    }
    return result;
    }
    };

    int main() {
    Matrix m1(3);
    Matrix m2(3);

    // Add the two matrices
    Matrix m3 = m1 + m2;

    // Subtract the two matrices
    Matrix m4 = m1 - m2;

    return 0;
    }
     
    1. LVV
      vector<vector<int>> data; он не охуеет от векторов?)
Top
Loading...