upper_bound.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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_UPPER_BOUND_H
  9. #define _LIBCPP___ALGORITHM_UPPER_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_copy_constructible.h>
  20. #include <__utility/move.h>
  21. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  22. # pragma GCC system_header
  23. #endif
  24. _LIBCPP_PUSH_MACROS
  25. #include <__undef_macros>
  26. _LIBCPP_BEGIN_NAMESPACE_STD
  27. template <class _AlgPolicy, class _Compare, class _Iter, class _Sent, class _Tp, class _Proj>
  28. _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 _Iter
  29. __upper_bound(_Iter __first, _Sent __last, const _Tp& __value, _Compare&& __comp, _Proj&& __proj) {
  30. auto __len = _IterOps<_AlgPolicy>::distance(__first, __last);
  31. while (__len != 0) {
  32. auto __half_len = std::__half_positive(__len);
  33. auto __mid = _IterOps<_AlgPolicy>::next(__first, __half_len);
  34. if (std::__invoke(__comp, __value, std::__invoke(__proj, *__mid)))
  35. __len = __half_len;
  36. else {
  37. __first = ++__mid;
  38. __len -= __half_len + 1;
  39. }
  40. }
  41. return __first;
  42. }
  43. template <class _ForwardIterator, class _Tp, class _Compare>
  44. _LIBCPP_NODISCARD_EXT inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 _ForwardIterator
  45. upper_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value, _Compare __comp) {
  46. static_assert(is_copy_constructible<_ForwardIterator>::value, "Iterator has to be copy constructible");
  47. return std::__upper_bound<_ClassicAlgPolicy>(
  48. std::move(__first), std::move(__last), __value, std::move(__comp), std::__identity());
  49. }
  50. template <class _ForwardIterator, class _Tp>
  51. _LIBCPP_NODISCARD_EXT inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 _ForwardIterator
  52. upper_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value) {
  53. return std::upper_bound(std::move(__first), std::move(__last), __value, __less<>());
  54. }
  55. _LIBCPP_END_NAMESPACE_STD
  56. _LIBCPP_POP_MACROS
  57. #endif // _LIBCPP___ALGORITHM_UPPER_BOUND_H