C++ 程序重载加法运算符以相加两个矩阵


假设我们有两个矩阵 mat1 和 mat2。我们将必须相加这两个矩阵并构成第三个矩阵。我们必须通过重载加法运算符来执行此操作。

因此,如果输入为

58
96
79


83
47
63

那么输出将为

1311
1313
1312

为了解决这个问题,我们将遵循以下步骤 -

  • 重载加法运算符,这将以另一个矩阵 mat 作为第二个参数

  • 定义一个空白的二维数组 vv

  • 定义一个二维数组 vv,并将当前矩阵元素加载到其中

  • 对于初始化 i := 0,当 i < vv 的大小时,更新(将 i 递增 1),执行

    • 对于初始化 j := 0,当 j < vv[0] 的大小时,更新(将 j 递增 1),执行

      • vv[i, j] := vv[i, j] + mat.a[i, j]
  • 使用 vv 返回一个新矩阵

让我们查看以下实现以获得更好的理解 -

示例

Open Compiler
#include <iostream> #include <vector> using namespace std; class Matrix { public: Matrix() {} Matrix(const Matrix& x) : a(x.a) {} Matrix(const vector<vector<int>>& v) : a(v) {} Matrix operator+(const Matrix&); vector<vector<int>> a; void display(){ for(int i = 0; i<a.size(); i++){ for(int j = 0; j<a[i].size(); j++){ cout << a[i][j] << " "; } cout << endl; } } }; Matrix Matrix::operator+(const Matrix& m){ vector<vector<int>> vv = a; for (int i=0; i<vv.size(); i++){ for (int j=0; j<vv[0].size(); j++){ vv[i][j] += m.a[i][j]; } } return Matrix(vv); } int main(){ vector<vector<int>> mat1 = {{5,8},{9,6},{7,9}}; vector<vector<int>> mat2 = {{8,3},{4,7},{6,3}}; int r = mat1.size(); int c = mat1[0].size(); Matrix m1(mat1), m2(mat2), res; res = m1 + m2; res.display(); }

输入

{{5,8},{9,6},{7,9}}, {{8,3},{4,7},{6,3}}

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

13 11
13 13
13 12

更新于: 07-10-2021

3K+ 浏览量

开启您的 事业

完成课程即可获得认证

开始吧
广告