-
Notifications
You must be signed in to change notification settings - Fork 0
/
vector.h
143 lines (112 loc) · 2.95 KB
/
vector.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
139
140
141
142
143
#ifndef VECTOR_H
#define VECTOR_H
#include <initializer_list>
#include <cmath>
#include <cstdlib>
#include <assert.h>
#include <ostream>
template <size_t size>
class Vector
{
public:
Vector()
{
static_assert(size > 0, "Wrong size\n");
}
Vector(std::initializer_list<double> list)
{
static_assert(size > 0, "Wrong size\n");
for (size_t i = 0; i < size && i < list.size(); i++)
dataArray[i] = *(list.begin() + i);
}
Vector& operator+= (const Vector& b)
{
for (size_t i = 0; i < size; i++)
dataArray[i] += b.dataArray[i];
return (*this);
}
Vector& operator-= (const Vector& b)
{
for (size_t i = 0; i < size; i++)
dataArray[i] -= b.dataArray[i];
return (*this);
}
Vector& operator*= (double b)
{
for (size_t i = 0; i < size; i++)
dataArray[i] *= b;
return (*this);
}
Vector operator+ (const Vector& b) const
{
Vector a1 = (*this);
for (size_t i = 0; i < size; i++)
a1.dataArray[i] += b.dataArray[i];
return a1;
}
Vector operator- (const Vector& b) const
{
Vector a1 = (*this);
for (size_t i = 0; i < size; i++)
a1.dataArray[i] -= b.dataArray[i];
return a1;
}
Vector operator- () const
{
Vector a1 = (*this);
for (size_t i = 0; i < size; i++)
a1.dataArray[i] = - a1.dataArray[i];
return a1;
}
Vector operator* (double b) const
{
Vector a1 = (*this);
for (size_t i = 0; i < size; i++)
a1.dataArray[i] *= b;
return a1;
}
friend Vector operator*(double b, const Vector& a)
{
Vector a1 = a;
for (size_t i = 0; i < size; i++)
a1.dataArray[i] *= b;
return a1;
}
Vector operator/ (double b) const
{
Vector a1 = (*this);
for (size_t i = 0; i < size; i++)
a1.dataArray[i] /= b;
return a1;
}
double& operator[] (size_t ind)
{
if (ind >= size)
throw ("Wrong index");
return dataArray[ind];
}
double manhattanDistance()
{
double norm = 0;
for (size_t i = 0; i < size; i++)
norm += fabs(dataArray[i]);
return norm;
}
double euclidDistance()
{
double norm = 0;
for (size_t i = 0; i < size; i++)
norm += dataArray[i] * dataArray[i];
return sqrt(norm);
}
friend std::ostream& operator<< (std::ostream& os, const Vector& v)
{
for (size_t i = 0; i < size - 1; i++)
os << v.dataArray[i] << " ";
os << v.dataArray[size - 1] << std::endl;
return os;
}
private:
double dataArray[size];
};
#endif //VECTOR_H