Skip to content

Commit 912e19d

Browse files
committed
Add equality/inequality operator
1 parent bc0fe03 commit 912e19d

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

source-code/convolution/cpp/src/convolution/matrices.cpp

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ Matrix& Matrix::operator=(const Matrix& other) {
1919
}
2020
return *this;
2121
}
22+
2223
Matrix::Matrix(Matrix&& other) noexcept :
2324
rows_{other.rows_}, cols_{other.cols_},
2425
data_{std::move(other.data_)} {
@@ -38,6 +39,23 @@ Matrix& Matrix::operator=(Matrix&& other) noexcept {
3839
return *this;
3940
}
4041

42+
bool Matrix::operator==(const Matrix& other) const {
43+
if (this == &other) {
44+
return true;
45+
}
46+
if (rows_ != other.rows_ || cols_ != other.cols_) {
47+
return false;
48+
}
49+
for (int i = 0; i < rows_; ++i) {
50+
for (int j = 0; j < cols_; ++j) {
51+
if ((*this)(i, j) != other(i, j)) {
52+
return false;
53+
}
54+
}
55+
}
56+
return true;
57+
}
58+
4159
std::ostream& operator<<(std::ostream& os, const Matrix& m) {
4260
for (int i = 0; i < m.rows_; ++i) {
4361
for (int j = 0; j < m.cols_; ++j) {

source-code/convolution/cpp/src/convolution/matrices.h

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,19 +12,21 @@ struct Matrix {
1212
std::unique_ptr<double[]> data_;
1313
public:
1414
Matrix(int rows, int cols) :
15-
rows_(rows), cols_(cols), data_(new double[rows * cols]) {}
15+
rows_(rows), cols_(cols), data_(new double[rows*cols]) {}
1616
// copy constructor & assignment operator
1717
Matrix(const Matrix& other);
1818
Matrix& operator=(const Matrix& other);
1919
// move constructor & assignment operator
2020
Matrix(Matrix&& other) noexcept;
2121
Matrix& operator=(Matrix&& other) noexcept;
2222
// matrix indexing by row and column
23-
double& operator()(int i, int j) { return data_[i * cols_ + j]; }
24-
double operator()(int i, int j) const { return data_[i * cols_ + j]; }
23+
double& operator()(int i, int j) { return data_[i*cols_ + j]; }
24+
double operator()(int i, int j) const { return data_[i*cols_ + j]; }
2525
// getters for number of rows and columns
2626
int rows() const { return rows_; }
2727
int cols() const { return cols_; }
28+
bool operator==(const Matrix& other) const;
29+
bool operator!=(const Matrix& other) const { return !(*this == other); }
2830
// accessors for the data
2931
double* data() { return data_.get(); }
3032
const double* data() const { return data_.get(); }

0 commit comments

Comments
 (0)