-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatrix.hpp
122 lines (99 loc) · 2.38 KB
/
matrix.hpp
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#pragma once
#include <cassert>
#include <stdexcept>
namespace cnn_net {
class matrix {
public:
matrix() = default;
matrix(matrix&& m) : data_(m.data_), rows_(m.rows_), cols_(m.cols_) {
}
~matrix() {
delete[] data_;
}
matrix(const matrix& m) : rows_(m.rows_), cols_(m.cols_) {
copy(m);
}
matrix& operator= (const matrix& m) {
if (this == &m) {
return *this;
}
if (rows_ != m.rows_ || cols_ != m.cols_) {
delete[] data_;
rows_ = m.rows_;
cols_ = m.cols_;
assert(rows_ != 0 && cols_ != 0);
data_ = new double[rows_ * cols_]();
}
copy(m);
return *this;
}
matrix& operator= (matrix&& m) {
if (this == &m) {
return *this;
}
delete[] data_;
data_ = m.data_;
rows_ = m.rows_;
cols_ = m.cols_;
m.reset();
return *this;
}
matrix(unsigned rows, unsigned cols) : rows_(rows), cols_(cols) {
if (rows == 0 || cols == 0)
throw std::invalid_argument("Matrix constructor has 0 size");
data_ = new double[rows * cols]();
}
matrix(unsigned rows) : rows_(rows), cols_(1) {
if (rows == 0)
throw std::invalid_argument("Matrix constructor has 0 size");
data_ = new double[rows * cols_]();
}
double& operator() (unsigned row, unsigned col) {
if (row >= rows_ || col >= cols_)
throw std::invalid_argument("Matrix subscript out of bounds");
return data_[cols_*row + col];
}
double operator() (unsigned row, unsigned col) const {
if (row >= rows_ || col >= cols_)
throw std::invalid_argument("const Matrix subscript out of bounds");
return data_[cols_*row + col];
}
double& operator() (unsigned row) {
assert(cols_ == 1);
if (row >= rows_)
throw std::invalid_argument("Matrix subscript out of bounds");
return data_[cols_*row];
}
double operator() (unsigned row) const {
assert(cols_ == 1);
if (row >= rows_)
throw std::invalid_argument("const Matrix subscript out of bounds");
return data_[cols_*row];
}
size_t rows() const {
return rows_;
}
size_t cols() const {
return cols_;
}
size_t size() const {
return rows_ * cols_;
}
void reset() {
data_ = nullptr;
rows_ = 0;
cols_ = 0;
}
private:
void copy(const matrix& m) {
for (size_t i = 0; i < rows_*cols_; ++i) {
data_[i] = m.data_[i];
}
}
private:
size_t rows_ = 0;
size_t cols_ = 0;
double* data_ = nullptr;;
};
using matrix_1d = matrix;
}