-
Notifications
You must be signed in to change notification settings - Fork 0
/
units.h
87 lines (81 loc) · 2.24 KB
/
units.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
#include <vector>
#include <algorithm>
#pragma once
namespace cunits {
/* Ideas for new features:
* 1. Uncertainty (a±b)
*/
enum BaseUnit { METER, KILOGRAM, SECOND, AMPERE, KELVIN, MOLE, CANDELA };
struct UnitPart {
BaseUnit type;
int exp;
UnitPart(BaseUnit _type, int _exp) {
type = _type;
exp = _exp;
}
};
static bool operator ==(UnitPart a, UnitPart b) {
return a.type == b.type && a.exp == b.exp;
}
class Unit {
public:
std::vector<UnitPart> parts;
double value;
Unit(double _value) {
value = _value;
}
Unit(std::vector<UnitPart> _parts, double _value) {
parts = _parts;
value = _value;
}
Unit(BaseUnit _type, double _value) {
parts.push_back(UnitPart(_type, 1));
value = _value;
}
};
// Unit Operators
static Unit operator *(Unit a, Unit b) {
std::vector<UnitPart> parts = a.parts;
for (UnitPart& part : b.parts) {
std::vector<UnitPart>::iterator it = std::find(parts.begin(), parts.end(), part);
if (it == parts.end()) {
parts.push_back(part);
}
else {
part.exp *= next(it)->exp;
}
}
return Unit(parts, a.value * b.value);
return a;
}
static Unit operator *(Unit u, double d) {
return Unit(u.parts, u.value * d);
}
static Unit operator *(double d, Unit u) {
return Unit(u.parts, u.value * d);
}
static Unit operator /(Unit a, Unit b) {
for (UnitPart& p : b.parts) {
p.exp *= -1;
}
b.value = 1 / b.value;
return a * b;
}
static Unit operator /(Unit u, double d) {
u.value /= d;
return u;
}
static Unit operator /(double d, Unit u) {
for (UnitPart& p : u.parts) {
p.exp *= -1;
}
u.value = d / u.value;
return u;
}
Unit operator "" c(unsigned long long int i) {
return Unit(i);
}
Unit operator "" c(long double d) {
return Unit(d);
}
}