-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmatrix.h
More file actions
107 lines (90 loc) · 1.74 KB
/
matrix.h
File metadata and controls
107 lines (90 loc) · 1.74 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
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
// cpp-simple-matrix v1.0
// GitHub: https://github.com/yipo/cpp-simple-matrix
// Author: Yi-Pu Guo (YiPo)
// License: MIT
#ifndef _MATRIX_H_
#define _MATRIX_H_
#include <cstring>
template <typename T>
class matrix {
int m,n;
T *buf;
public:
matrix() : m(0),n(0),buf(new T[0]) {}
matrix(int m,int n) : m(m),n(n),buf(new T[m*n]) {}
matrix(const matrix &mat) : m(mat.m),n(mat.n),buf(new T[m*n]) {
std::memcpy(buf,mat.buf,m*n*sizeof(T));
}
~matrix() {
delete [] buf;
}
matrix &operator =(const matrix &mat) {
if (this!=&mat) {
if (mat.m*mat.n!=m*n) {
delete [] buf;
buf=new T[mat.m*mat.n];
}
m=mat.m,n=mat.n;
std::memcpy(buf,mat.buf,m*n*sizeof(T));
}
return *this;
}
friend void swap(matrix<T> &a,matrix<T> &b) {
int m=a.m;a.m=b.m,b.m=m;
int n=a.n;a.n=b.n,b.n=n;
T *t=a.buf;a.buf=b.buf,b.buf=t;
}
/*
* Get the size of this matrix.
*/
int get_m() const {
return m;
}
int get_n() const {
return n;
}
/*
* Access the element via the `at' member function.
*/
T &at(int i,int j) {
return buf[i*n+j];
}
const T &at(int i,int j) const {
return buf[i*n+j];
}
/*
* Access the element by the way of functor.
*/
T &operator ()(int i,int j) {
return buf[i*n+j];
}
const T &operator ()(int i,int j) const {
return buf[i*n+j];
}
/*
* Access the element via the [] operator.
*/
private:
class row {
T *buf;
private:
row(T *buf) : buf(buf) {}
public:
T &operator [](int j) {
return buf[j];
}
const T &operator [](int j) const {
return buf[j];
}
friend class matrix;
// So that only the matrix class can create a row object.
};
public:
row operator [](int i) {
return row(buf+i*n);
}
const row operator [](int i) const {
return row(buf+i*n);
}
};
#endif