Created
December 12, 2011 17:23
-
-
Save jorendorff/1468256 to your computer and use it in GitHub Desktop.
std::lower_bound
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @brief Finds the first position in which @a val could be inserted | |
* without changing the ordering. | |
* @param first An iterator. | |
* @param last Another iterator. | |
* @param val The search term. | |
* @return An iterator pointing to the first element "not less than" @a val, | |
* or end() if every element is less than @a val. | |
* @ingroup binarysearch | |
*/ | |
template<typename _ForwardIterator, typename _Tp> | |
_ForwardIterator | |
lower_bound(_ForwardIterator __first, _ForwardIterator __last, | |
const _Tp& __val) | |
{ | |
typedef typename iterator_traits<_ForwardIterator>::value_type | |
_ValueType; | |
typedef typename iterator_traits<_ForwardIterator>::difference_type | |
_DistanceType; | |
// concept requirements | |
__glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) | |
__glibcxx_function_requires(_LessThanOpConcept<_ValueType, _Tp>) | |
__glibcxx_requires_partitioned(__first, __last, __val); | |
_DistanceType __len = std::distance(__first, __last); | |
_DistanceType __half; | |
_ForwardIterator __middle; | |
while (__len > 0) | |
{ | |
__half = __len >> 1; | |
__middle = __first; | |
std::advance(__middle, __half); | |
if (*__middle < __val) | |
{ | |
__first = __middle; | |
++__first; | |
__len = __len - __half - 1; | |
} | |
else | |
__len = __half; | |
} | |
return __first; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment