aboutsummaryrefslogtreecommitdiff
path: root/src/vector.h
blob: 5e105c4435947a6ff96003659ce9b2ec0fcaafbb (plain)
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
#pragma once

#include <cmath>

inline double sq(double x) noexcept {
	return x * x;
}

template <typename T>
struct Vector {
	T data[2];

	T comp(int x, int y) const {
		return x*data[0] + y*data[1];
	}

	T norm() const {
		return std::sqrt(sq(data[0]) + sq(data[1]));
	}

	T& operator[](std::size_t i) {
		return data[i];
	}

	T operator[](std::size_t i) const {
		return data[i];
	}

	Vector<T> operator*(T scalar) const {
		return Vector<T>{
			data[0] * scalar,
			data[1] * scalar
		};
	}

	Vector<T> operator-() const {
		return -1 * *this;
	}

	Vector<T>& operator+=(const Vector<T>& rhs) {
		data[0] += rhs[0];
		data[1] += rhs[1];
		return *this;
	}
};

template <typename T>
Vector<T> operator*(T scalar, const Vector<T>& v) {
	return Vector<T>{
		v[0] * scalar,
		v[1] * scalar
	};
}

template <typename T, typename W>
Vector<T> operator-(const Vector<T>& a, const Vector<W>& b) {
	return Vector<T>{
		a[0] - b[0],
		a[1] - b[1]
	};
}

template <typename T, typename W>
Vector<T> operator+(const Vector<T>& a, const Vector<W>& b) {
	return Vector<T>{
		a[0] + b[0],
		a[1] + b[1]
	};
}