Загрузка...

Решить задачу на с++

Тема в разделе C/C++ создана пользователем Misodzi 19 дек 2022. 262 просмотра

  1. Misodzi
    Misodzi Автор темы 19 дек 2022 0 9 июн 2019
    Реализуй класс для хранения квадратной матрицы. перезагрузите метод + и -, сгенерируйте и обработайте ошибки
     
  2. brediska
    brediska 6 янв 2023 Заблокирован(а) 2794 30 май 2021
    Код
    #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