From 0887aee8c54d0ed51bb2031431e2bcdafebb4c6e Mon Sep 17 00:00:00 2001 From: Daniel Wilhelm Date: Fri, 18 Apr 2014 17:23:19 +0200 Subject: 5.13 --- zen/basic_math.h | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) (limited to 'zen/basic_math.h') 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 #include #include +#include #include #include @@ -40,6 +41,9 @@ std::pair minMaxElement(InputIterator first, Input template std::pair minMaxElement(InputIterator first, InputIterator last, Compare comp); +template //precondition: range must be sorted! +auto nearMatch(const T& val, InputIterator first, InputIterator last) -> typename std::iterator_traits::value_type; + template bool isNull(T value); @@ -198,6 +202,25 @@ std::pair minMaxElement(InputIterator first, Input } +template inline +auto nearMatch(const T& val, InputIterator first, InputIterator last) -> typename std::iterator_traits::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 inline bool isNull(T value) { -- cgit