File tree Expand file tree Collapse file tree 1 file changed +70
-0
lines changed
07 - Other Concepts/04 - Operator Overloading Expand file tree Collapse file tree 1 file changed +70
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < cmath>
2
+ #include < cstdio>
3
+ #include < vector>
4
+ #include < iostream>
5
+ #include < algorithm>
6
+ using namespace std ;
7
+
8
+ // Fix the member variable references
9
+ #define a matrix
10
+
11
+ class Matrix {
12
+ public:
13
+ vector<vector<int >> matrix;
14
+
15
+ Matrix operator +(const Matrix& other) {
16
+ Matrix result;
17
+
18
+ int n = matrix.size ();
19
+ int m = matrix[0 ].size ();
20
+
21
+ for (int i = 0 ; i < n; i++) {
22
+ vector<int > row;
23
+
24
+ for (int j = 0 ; j < m; j++) {
25
+ row.push_back (matrix[i][j] + other.matrix [i][j]);
26
+ }
27
+ result.matrix .push_back (row);
28
+ }
29
+
30
+ return result;
31
+ }
32
+ };
33
+
34
+ int main () {
35
+ int cases, k;
36
+ cin >> cases;
37
+ for (k = 0 ; k < cases; k++) {
38
+ Matrix x;
39
+ Matrix y;
40
+ Matrix result;
41
+ int n, m, i, j;
42
+ cin >> n >> m;
43
+ for (i = 0 ; i < n; i++) {
44
+ vector<int > b;
45
+ int num;
46
+ for (j = 0 ; j < m; j++) {
47
+ cin >> num;
48
+ b.push_back (num);
49
+ }
50
+ x.a .push_back (b); // Now 'a' refers to 'matrix'
51
+ }
52
+ for (i = 0 ; i < n; i++) {
53
+ vector<int > b;
54
+ int num;
55
+ for (j = 0 ; j < m; j++) {
56
+ cin >> num;
57
+ b.push_back (num);
58
+ }
59
+ y.a .push_back (b); // Now 'a' refers to 'matrix'
60
+ }
61
+ result = x + y;
62
+ for (i = 0 ; i < n; i++) {
63
+ for (j = 0 ; j < m; j++) {
64
+ cout << result.a [i][j] << " " ; // Now 'a' refers to 'matrix'
65
+ }
66
+ cout << endl;
67
+ }
68
+ }
69
+ return 0 ;
70
+ }
You can’t perform that action at this time.
0 commit comments