-
Notifications
You must be signed in to change notification settings - Fork 0
/
MinMax.h
72 lines (63 loc) · 1.59 KB
/
MinMax.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
#ifndef MINMAX_H
#define MINMAX_H
#include "Range.h"
#include <limits>
#include <algorithm>
namespace util {
template <typename T>
class MinMax {
public:
MinMax()
: min_(std::numeric_limits<T>::max())
, max_(std::numeric_limits<T>::lowest())
{}
MinMax(const T& a, const T& b)
: min_(std::min(a, b))
, max_(std::max(a, b))
{}
bool IsValid() const { return min_ <= max_; }
T Min() const { return IsValid() ? min_ : T{ 0 }; }
T Max() const { return IsValid() ? max_ : T{ 0 }; }
T Range() const { return IsValid() ? max_ - min_ : T{ 0 }; }
bool Contains(const T& value) const { return value >= min_ && value <= max_; }
operator util::Range<T>() const { return util::Range(Min(), Max()); }
void ExpandToContain(const T& newValue)
{
if (IsValid()) {
if (newValue < min_) {
min_ = newValue;
}
if (newValue > max_) {
max_ = newValue;
}
} else {
max_ = newValue;
min_ = newValue;
}
}
void SetMin(const T& newMin)
{
min_ = newMin;
max_ = std::max(max_, newMin);
}
void SetMax(const T& newMax)
{
min_ = std::min(min_, newMax);
max_ = newMax;
}
void SetRange(const T& a, const T& b)
{
min_ = std::min(a, b);
max_ = std::max(a, b);
}
void Reset()
{
min_ = std::numeric_limits<T>::max();
max_ = std::numeric_limits<T>::lowest();
}
private:
T min_;
T max_;
};
} // end namespace util
#endif // MINMAX_H