-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvector.h
More file actions
145 lines (124 loc) · 3.21 KB
/
vector.h
File metadata and controls
145 lines (124 loc) · 3.21 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
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
139
140
141
142
143
144
145
#ifndef VECTOR_H
#define VECTOR_H
#include <initializer_list>
namespace dd {
/**
* Fixed-size vector class.
*
* TODO: Write allocation-free assignment operators;
* work infix operators through assignment operators.
*/
template <unsigned size>
class Vector {
#define VECTOR_NAME "Vector"
private:
double data[size];
public:
/**
* Size getter
*/
constexpr double getSize() const { return size; }
/**
* Immutable get
*/
const double & operator[](unsigned index) const {
return data[index];
}
/**
* Mutable get
*/
double & operator[](unsigned index) {
return data[index];
}
/**
* Populate the vector with the given value.
*/
void fill(const double & value) {
for(unsigned i = 0; i < size; i++) {
data[i] = value;
}
}
/**
* Zero-fill
*/
void zero() { fill(0); }
/**
* Fill constructor
*/
Vector(const double & value) { fill(value); }
/**
* Scale the vector
*/
void scale(double scaleValue) {
for(unsigned i = 0; i < size; i++) {
data[i] *= scaleValue;
}
}
/**
* Zero constructor
*/
Vector() : Vector(0) { }
/**
* Copy constructor
*/
Vector(const Vector & other) {
for(unsigned i = 0; i < size; i++) {
data[i] = other[i];
}
}
/**
* Initializer-list constructor
*/
Vector(const std::initializer_list<double> & init) {
unsigned index = 0;
for(double val : init) {
data[index] = val;
index++;
}
}
/**
* Unary minus
*/
Vector operator-() const {
return Vector(*this).scale(-1);
}
/**
* Vector addition
*/
Vector operator+(const Vector & other) const {
Vector result;
for(unsigned i = 0; i < size; i++) {
result[i] = data[i] + other[i];
}
return result;
}
Vector & operator+=(const Vector & other) {
return *this = (*this + other);
}
/**
* Vector subtraction
*/
Vector operator-(const Vector & other) const {
return (*this) + (-Vector(other));
}
Vector & operator-=(const Vector & other) {
return *this = (*this - other);
}
/**
* Scaling
*/
Vector operator*(const double & factor) const {
Vector result(*this);
result.scale(-1);
return result;
}
Vector & operator*=(const double & factor) {
return *this = (*this * factor);
}
virtual string typeName() const { return VECTOR_NAME; }
static string staticTypeName() { return VECTOR_NAME; }
};
typedef Vector<2> Vector2d;
typedef Vector<3> Vector3d;
}
#endif // VECTOR_H