题解 | 计算两个矩阵的乘积(基于面向对象编程)

#include <iostream>
#include <vector>
using namespace std;
class Matrix {
  public:
    Matrix(int row, int col) {
        assign(row, col);
    }
    Matrix(int row, int col, int num) {
        assign(row, col, num);
    }
    void assign(int row, int col, int num = 0) {
        arrays.resize(row, vector<int>(col, num));
    }
    void resize(int row, int col) {
        arrays.resize(row, vector<int>(col));
    }
    int row()const {
        return arrays.size();
    }
    int col()const {
        return arrays[0].size();
    }
    int& value(int row, int col) {
        return arrays[row - 1][col - 1];
    }
    Matrix operator*(Matrix& matrix) {
        if (this->col() != matrix.row())
            throw "multiply illegal!";
        Matrix mul_result(this->row(), matrix.col());
        for (int i = 0; i < this->row(); i++) {
            for (int j = 0; j < matrix.col(); j++) {
                int temp = 0;
                for (int k = 0; k < this->col(); k++) {
                    temp += value(i + 1, k + 1) * matrix.value(k + 1, j + 1);
                }
                mul_result.value(i + 1, j + 1) = temp;
            }
        }
        return mul_result;
    }
  private:
    vector<vector<int>> arrays;
};

int main() {
    Matrix m1(2, 3), m2(3, 2);
    for (int i = 1; i <= 2; i++) {
        for (int j = 1; j <= 3; j++)
            cin >> m1.value(i, j);
    }
    for (int i = 1; i <= 3; i++) {
        for (int j = 1; j <= 2; j++)
            cin >> m2.value(i, j);
    }
    Matrix m3 = m1 * m2;
    for (int i = 1; i <= 2; i++) {
        for (int j = 1; j <= 2; j++) {
            cout << m3.value(i, j) << " ";
        }
        cout << endl;
    }
}

全部评论
接好运
点赞 回复 分享
发布于 01-05 13:32 广东

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务