-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatrix.h
More file actions
74 lines (62 loc) · 1.45 KB
/
Matrix.h
File metadata and controls
74 lines (62 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#pragma once
#include <iostream>
template<typename T>
class Matrix {
public:
Matrix(int n = 0, T defaultValue = T())
: n{ n }, vec(n * n, defaultValue)
{ }
T& operator ()(int row, int col) {
return vec[n * row + col];
}
const T& operator ()(int row, int col) const {
return vec[n * row + col];
}
int size() const {
return n;
}
Matrix<T> operator+(const Matrix<T>& m) const {
Matrix<T> r(size());
for (int i = 0; i < size(); ++i)
for (int j = 0; j < size(); ++j)
r(i, j) = (*this)(i, j) + m(i, j);
return r;
}
Matrix<T> operator-() const {
Matrix<T> r(size());
for (int i = 0; i < size(); ++i)
for (int j = 0; j < size(); ++j)
r(i, j) = -(*this)(i, j);
return r;
}
Matrix<T> operator-(const Matrix<T>& m) const {
return (*this) + -m;
}
bool operator==(const Matrix<T>& m) const {
for (int i = 0; i < size(); ++i)
for (int j = 0; j < size(); ++j)
if ((*this)(i, j) != m(i, j))
return false;
return true;
}
Matrix<T> operator*(const Matrix<T>& m) const {
Matrix<T> r(size());
for (int i = 0; i < size(); ++i)
for (int j = 0; j < size(); ++j)
for (int k = 0; k < size(); ++k)
r(i, j) += (*this)(i, k) * m(k, j);
return r;
}
private:
int n;
std::vector<T> vec;
};
template<typename T>
std::ostream& operator<<(std::ostream& out, const Matrix<T>& mat) {
for (int i = 0; i < mat.size(); ++i) {
for (int j = 0; j < mat.size(); ++j)
out << mat(i, j) << ' ';
out << '\n';
}
return out;
}