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
|
#pragma once
#include <util/generic/noncopyable.h>
#include <util/system/yassert.h>
#include <util/system/defaults.h>
#include <string.h>
template <typename T>
class TMatrix: TNonCopyable {
// Constructor/Destructor
public:
TMatrix()
: Buf(nullptr)
, Arr(nullptr)
, M(0)
, N(0)
, BufSize(0)
{
}
TMatrix(size_t m, size_t n)
: Buf(new T[m * n])
, Arr(Buf)
, M(m)
, N(n)
, BufSize(m * n)
{
}
TMatrix(size_t m, size_t n, T* buf)
: Buf(nullptr)
, Arr(buf)
, M(m)
, N(n)
, BufSize(m * n)
{
}
~TMatrix() {
delete[] Buf;
}
// Properties/Methods
public:
void Clear() {
M = N = 0;
}
void ReDim(size_t m, size_t n) {
Y_ASSERT(m >= 1 && n >= 1);
size_t newSize = m * n;
if (newSize > BufSize) {
T* newBuf = new T[newSize];
delete[] Buf;
Arr = Buf = newBuf;
BufSize = newSize;
}
M = m;
N = n;
}
size_t Width() const {
return N;
}
size_t Height() const {
return M;
}
// Access element matrix[i][j]
T* operator[](size_t i) {
Y_ASSERT(i >= 0 && i < M);
return Arr + i * N;
}
// Access element matrix[i][j]
const T* operator[](size_t i) const {
Y_ASSERT(i >= 0 && i < M);
return Arr + i * N;
}
// Access element matrix(i, j)
T& operator()(size_t i, size_t j) {
Y_ASSERT(i >= 0 && i < M && j >= 0 && j < N);
return Arr[i * N + j];
}
// Access element matrix(i, j)
const T& operator()(size_t i, size_t j) const {
Y_ASSERT(i >= 0 && i < M && j >= 0 && j < N);
return Arr[i * N + j];
}
void Zero() {
memset((void*)Arr, 0, M * N * sizeof(T));
}
void Fill(T value) {
for (T *p = Arr, *end = Arr + M * N; p < end; ++p)
*p = value;
}
private:
T* Buf;
T* Arr;
size_t M, N;
size_t BufSize;
};
|