diff options
Diffstat (limited to 'zen/basic_math.h')
-rw-r--r-- | zen/basic_math.h | 23 |
1 files changed, 23 insertions, 0 deletions
diff --git a/zen/basic_math.h b/zen/basic_math.h index d83a7f77..89d9d6c0 100644 --- a/zen/basic_math.h +++ b/zen/basic_math.h @@ -10,6 +10,7 @@ #include <algorithm> #include <iterator> #include <limits> +#include <cmath> #include <functional> #include <cassert> @@ -40,6 +41,9 @@ std::pair<InputIterator, InputIterator> minMaxElement(InputIterator first, Input template <class InputIterator, class Compare> std::pair<InputIterator, InputIterator> minMaxElement(InputIterator first, InputIterator last, Compare comp); +template <class T, class InputIterator> //precondition: range must be sorted! +auto nearMatch(const T& val, InputIterator first, InputIterator last) -> typename std::iterator_traits<InputIterator>::value_type; + template <class T> bool isNull(T value); @@ -198,6 +202,25 @@ std::pair<InputIterator, InputIterator> minMaxElement(InputIterator first, Input } +template <class T, class InputIterator> inline +auto nearMatch(const T& val, InputIterator first, InputIterator last) -> typename std::iterator_traits<InputIterator>::value_type +{ + if (first == last) + return 0; + + assert(std::is_sorted(first, last)); + InputIterator it = std::lower_bound(first, last, val); + if (it == last) + return *--last; + if (it == first) + return *first; + + const auto nextVal = *it; + const auto prevVal = *--it; + return val - prevVal < nextVal - val ? prevVal : nextVal; +} + + template <class T> inline bool isNull(T value) { |