-
Notifications
You must be signed in to change notification settings - Fork 1
/
Vector.h
105 lines (89 loc) · 2.15 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
#ifndef VECTOR_H
#define VECTOR_H
#include <cmath>
template <typename T>
class Vector
{
public:
Vector(int n)
: n(n),
data(new T[n])
{
for (int i = 0; i < n; i++)
{
data[i] = 0;
}
}
Vector(const Vector &other)
: Vector(other.len())
{
for (auto i = 0; i < other.len(); i++)
data[i] = other.data[i];
}
double norm() const
{
double norm = 0;
for (int i = 0; i < n; i++)
{
norm += data[i] * data[i];
}
return sqrt(norm);
}
inline T& operator[](int i) const
{
return data[i];
}
inline T operator()(int i) const
{
return data[i];
}
template <typename U>
Vector<typename std::common_type<T, U>::type> operator/(const U scal)
{
Vector<typename std::common_type<T, U>::type> v(n);
for (int i = 0; i < n; i++)
v[i] = data[i] / scal;
return v;
}
template <typename U>
Vector<typename std::common_type<T, U>::type> operator*(const U scal)
{
Vector<typename std::common_type<T, U>::type> v(n);
for (int i = 0; i < n; i++)
v[i] = data[i] * scal;
return v;
}
template <typename U>
Vector<typename std::common_type<T, U>::type> operator+(const Vector<U> &other)
{
Vector<typename std::common_type<T, U>::type> v(n);
for (int i = 0; i < n; i++)
v[i] = data[i] + other[i];
return v;
}
template <typename U>
Vector<typename std::common_type<T, U>::type> operator-(const Vector<U> &other)
{
Vector<typename std::common_type<T, U>::type> v(n);
for (int i = 0; i < n; i++)
v[i] = data[i] - other[i];
return v;
}
void print()
{
std::cout << "[";
for (int i = 0; i < n; i++)
{
std::cout << data[i] << ",";
}
std::cout << "]\n";
}
int len() const
{
return n;
}
private:
int n;
T *data;
};
#endif