lower_bound.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. //===----------------------------------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #ifndef _LIBCPP___ALGORITHM_LOWER_BOUND_H
  9. #define _LIBCPP___ALGORITHM_LOWER_BOUND_H
  10. #include <__algorithm/comp.h>
  11. #include <__algorithm/half_positive.h>
  12. #include <__algorithm/iterator_operations.h>
  13. #include <__config>
  14. #include <__functional/identity.h>
  15. #include <__functional/invoke.h>
  16. #include <__iterator/advance.h>
  17. #include <__iterator/distance.h>
  18. #include <__iterator/iterator_traits.h>
  19. #include <__type_traits/is_callable.h>
  20. #include <__type_traits/remove_reference.h>
  21. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  22. # pragma GCC system_header
  23. #endif
  24. _LIBCPP_BEGIN_NAMESPACE_STD
  25. template <class _AlgPolicy, class _Iter, class _Sent, class _Type, class _Proj, class _Comp>
  26. _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20
  27. _Iter __lower_bound(_Iter __first, _Sent __last, const _Type& __value, _Comp& __comp, _Proj& __proj) {
  28. auto __len = _IterOps<_AlgPolicy>::distance(__first, __last);
  29. while (__len != 0) {
  30. auto __l2 = std::__half_positive(__len);
  31. _Iter __m = __first;
  32. _IterOps<_AlgPolicy>::advance(__m, __l2);
  33. if (std::__invoke(__comp, std::__invoke(__proj, *__m), __value)) {
  34. __first = ++__m;
  35. __len -= __l2 + 1;
  36. } else {
  37. __len = __l2;
  38. }
  39. }
  40. return __first;
  41. }
  42. template <class _ForwardIterator, class _Tp, class _Compare>
  43. _LIBCPP_NODISCARD_EXT inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20
  44. _ForwardIterator lower_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value, _Compare __comp) {
  45. static_assert(__is_callable<_Compare, decltype(*__first), const _Tp&>::value,
  46. "The comparator has to be callable");
  47. auto __proj = std::__identity();
  48. return std::__lower_bound<_ClassicAlgPolicy>(__first, __last, __value, __comp, __proj);
  49. }
  50. template <class _ForwardIterator, class _Tp>
  51. _LIBCPP_NODISCARD_EXT inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20
  52. _ForwardIterator lower_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value) {
  53. return std::lower_bound(__first, __last, __value, __less<>());
  54. }
  55. _LIBCPP_END_NAMESPACE_STD
  56. #endif // _LIBCPP___ALGORITHM_LOWER_BOUND_H