Skip to content

Commit 236afbc

Browse files
committed
operator+ implemented
1 parent 888affa commit 236afbc

File tree

3 files changed

+71
-2
lines changed

3 files changed

+71
-2
lines changed

Variants/Lab_12/var_12/main.cpp

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -119,12 +119,29 @@ int main() {
119119

120120
cout << m10.get(0, 0) << " at 0, 0" << endl
121121
<< m10.get(9, 9) << " at 9, 9" << endl
122-
<< m10.get(5, 5) << " at 5, 5" << endl;
122+
<< m10.get(5, 5) << " at 5, 5" << endl << endl;
123123

124124
/*
125125
// Error in 'get' operator: Invalid index
126126
cout << m10.get(10, 10) << " at 10, 10" << endl;
127127
*/
128128

129-
129+
m10.transpose().print();
130+
m9.transpose().print();
131+
132+
Matrix test(
133+
{
134+
{1, 2, 3},
135+
{4, 5, 6},
136+
{7, 8, 9}
137+
}
138+
);
139+
140+
test.print();
141+
test.transpose().print();
142+
143+
// operators test
144+
145+
Matrix summ = Matrix(5, 1) + Matrix(5, 2);
146+
summ.print();
130147
}

Variants/Lab_12/var_12/matrix.cpp

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,4 +101,46 @@ unsigned int get_size(vector <vector <double>> arr) {
101101
}
102102
}
103103
return size;
104+
}
105+
106+
// преобразования
107+
108+
void swap(double *d1, double *d2) {
109+
double temp = *d1;
110+
*d1 = *d2;
111+
*d2 = temp;
112+
}
113+
114+
Matrix& Matrix::transpose() {
115+
for (int y = 0; y < this->size() - 1; y++) {
116+
for (int x = y + 1; x < this->size(); x++) {
117+
swap(&arr[y][x], &arr[x][y]);
118+
}
119+
}
120+
return *this;
121+
}
122+
123+
// операторы
124+
125+
Matrix& Matrix::operator+=(const Matrix& m) {
126+
try {
127+
if (arr.size() == m.arr.size()) {
128+
for (int x = 0; x < m.arr.size(); x++) {
129+
for (int y = 0; y < m.arr.size(); y++) {
130+
arr[y][x] += m.arr[y][x];
131+
}
132+
}
133+
} else {
134+
throw "Matrices have different sizes";
135+
}
136+
} catch (const char *s) {
137+
cerr << "Error in + operator: " << s << endl;
138+
exit(1);
139+
}
140+
return *this;
141+
}
142+
143+
Matrix operator+(Matrix a, const Matrix& b) {
144+
a += b;
145+
return a;
104146
}

Variants/Lab_12/var_12/matrix.h

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,14 @@ class Matrix {
2222
const unsigned int size();
2323

2424
void print();
25+
26+
// преобразования
27+
28+
Matrix& transpose();
29+
30+
// операторы
31+
32+
Matrix& operator+=(const Matrix& x);
33+
friend Matrix operator+(Matrix a, const Matrix &b);
34+
2535
};

0 commit comments

Comments
 (0)