Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ โหลดโอเปอเรเตอร์บวก (+) สำหรับบวกแมทริกซ์


สมมติว่าเรามีแมทริกซ์ mat1 และ mat2 เราต้องบวกทั้งสองแมทริกซ์ให้ได้แมทริกซ์ที่สาม โดยการโหลดโอเปอเรเตอร์บวก (+)

เช่น mat1 = [[5,8],[9,6],[7,9]], mat2 = [[8,3],[4,7],[6,3]] ผลลัพธ์:

1311
1313
1312

ขั้นตอนการแก้ปัญหา

  • โหลดโอเปอเรเตอร์ + รับอีกแมทริกซ์หนึ่งเป็นอาร์กิวเมนต์
  • สร้างอาเรย์ 2 มิติ vv คัดลอกข้อมูลแมทริกซ์ปัจจุบัน
  • วนลูปบวก vv[i][j] += mat.a[i][j]
  • คืนค่าแมทริกซ์ใหม่จาก vv

ตัวอย่างโค้ด

#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}};    Matrix m1(mat1), m2(mat2), res;    res = m1 + m2;    res.display(); }

อินพุต

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

เอาต์พุต

13 11 13 13 13 12