-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUtils_2.h
138 lines (111 loc) · 2.48 KB
/
Utils_2.h
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#ifndef UTILS_2
#define UTILS_2
#include "Functions.h" //uniform_random
#include "Matrix.h"
/************************************************************************
*
* IntArray
*
************************************************************************/
// M by N matrix of integer values
class IntArray {
public:
int *Elements;
int M, N;
public:
IntArray() :
Elements(NULL), M(0), N(0) {
}
IntArray(int p_M, int p_N) :
Elements(NULL), M(0), N(0) {
Allocate(p_M, p_N);
}
~IntArray() {
deAllocate();
}
void Allocate(int p_M, int p_N) {
if ((M != p_M) || (N != p_N)) {
deAllocate();
M = p_M;
N = p_N;
Elements = new int[M * N];
}
}
void deAllocate() {
M = 0;
N = 0;
if (Elements != NULL)
delete [] Elements;
Elements = NULL;
}
int &Element(int i, int j) {
return Elements[i * N + j];
}
};
/************************************************************************
*
* Vector
*
************************************************************************/
class vector {
public:
double *Elements;
int CountElements;
public:
vector(int p_Elements = 0) :
Elements(NULL), CountElements(0) {
Allocate(p_Elements);
}
~vector() {
deAllocate();
}
int GetSize() {
return CountElements;
}
double &operator[](int i) {
return Elements[i];
}
// Allocate an empty vector of length p_Elements
void Allocate(int p_Elements) {
if (CountElements != p_Elements) { // If new size is different, deallocate and allocate with new size
deAllocate();
if (p_Elements != 0) {
Elements = new double[p_Elements];
CountElements = p_Elements;
}
}
}
// Deallocate Elements to avoid memory leak
void deAllocate() {
if (Elements != NULL)
delete [] Elements;
Elements = NULL;
CountElements = 0;
}
// Operator overload: Copy p_Vector to this vector
vector &operator=(vector &p_Vector) {
Allocate(p_Vector.CountElements);
for (int i = 0; i < CountElements; i++)
Elements[i] = p_Vector.Elements[i];
return *this;
}
// Operator overload: copy a column vector to this vector //TODO: column_vector!!!
vector &operator=(column_vector &p_Vector) {
Allocate(p_Vector.M);
for (int i = 0; i < CountElements; i++)
Elements[i] = p_Vector.Elements[i].val;
return *this;
}
};
// Operator overload for outputting a vector to an ostream
inline std::ostream &operator<<(std::ostream &s, vector &v) {
s << "[";
for (int i = 0; i < v.GetSize(); i++) {
if (i != 0)
s << " ";
s << v[i];
}
s << "]";
return s;
};
#endif