/
vector.hpp
130 lines (111 loc) · 3.14 KB
/
vector.hpp
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
#ifndef TRIVIAL_VECTOR_HPP
#define TRIVIAL_VECTOR_HPP
#include <cmath>
#include <array>
#include <ostream>
#include <boost/operators.hpp>
namespace trivial
{
template <unsigned N, typename T = int>
struct vector : std::array<T, N>
, boost::additive1<vector<N, T>>
, boost::multiplicative2<vector<N, T>, T>
, boost::equality_comparable<vector<N, T>>
{
typedef std::array<T, N> base_type;
static const unsigned dimension = N;
vector ()
{
for (auto i = this->begin(); i != this->end(); ++i)
*i = 0;
}
template <typename T2>
explicit vector (vector<N, T2> const& other)
{
for (unsigned i = 0; i < N; ++i)
(*this)[i] = other[i];
}
vector& operator*= (T val)
{
for (unsigned i = 0; i < N; ++i)
(*this)[i] *= val;
return *this;
}
bool operator== (vector const& other) const
{
for (unsigned i = 0; i < N; ++i)
if ((*this)[i] != other[i])
return false;
return true;
}
vector& operator+= (vector const& other)
{
for (unsigned i = 0; i < N; ++i)
(*this)[i] += other[i];
return *this;
}
vector& operator-= (vector const& other)
{
for (unsigned i = 0; i < N; ++i)
(*this)[i] -= other[i];
return *this;
}
vector& operator/= (T val)
{
return *this *= 1/val;
}
};
template <unsigned N, typename T>
T abs2 (vector<N, T> const& v)
{
T res = 0;
for (unsigned i = 0; i < v.size(); ++i)
res += v[i] * v[i];
return res;
}
template <unsigned N, typename T>
T abs_1 (vector<N, T> const& v)
{
T res = 0;
for (unsigned i = 0; i < v.size(); ++i)
res += std::abs(v[i]);
return res;
}
template <unsigned N, typename T>
T abs_inf (vector<N, T> const& v)
{
T res = 0;
for (unsigned i = 0; i < v.size(); ++i)
res = std::max(res, abs(v[i]));
return res;
}
template <unsigned N, typename T>
float abs (vector<N, T> const& v)
{
return std::sqrt(float(abs2(v)));
}
template <typename T>
T const& get_unit_vector (unsigned n)
{
static T unit_vectors[T::dimension + 1];
static bool initialized = false;
if (!initialized)
{
for (unsigned i = 0; i < T::dimension; ++i)
for (unsigned j = 0; j < T::dimension; ++j)
unit_vectors[i][j] = (i == j) ? 1 : 0;
initialized = true;
}
return unit_vectors[std::min(n, unsigned(T::dimension))];
}
template<unsigned N, typename T>
std::ostream & operator<<(std::ostream & out, const vector<N, T> & p)
{
out << "(";
for(unsigned n = 0; n < N - 1; ++n)
out << p[n] << ",";
out << p[N - 1] << ")";
return out;
}
}
#endif