Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

80 linhas
2.7KB

  1. /// \file
  2. // Range v3 library
  3. //
  4. // Copyright Eric Niebler 2013-present
  5. //
  6. // Use, modification and distribution is subject to the
  7. // Boost Software License, Version 1.0. (See accompanying
  8. // file LICENSE_1_0.txt or copy at
  9. // http://www.boost.org/LICENSE_1_0.txt)
  10. //
  11. // Project home: https://github.com/ericniebler/range-v3
  12. //
  13. #ifndef RANGES_V3_ALGORITHM_BINARY_SEARCH_HPP
  14. #define RANGES_V3_ALGORITHM_BINARY_SEARCH_HPP
  15. #include <functional>
  16. #include <utility>
  17. #include <range/v3/range_fwd.hpp>
  18. #include <range/v3/algorithm/lower_bound.hpp>
  19. #include <range/v3/functional/comparisons.hpp>
  20. #include <range/v3/functional/identity.hpp>
  21. #include <range/v3/functional/invoke.hpp>
  22. #include <range/v3/iterator/concepts.hpp>
  23. #include <range/v3/iterator/traits.hpp>
  24. #include <range/v3/range/access.hpp>
  25. #include <range/v3/range/concepts.hpp>
  26. #include <range/v3/range/traits.hpp>
  27. #include <range/v3/utility/static_const.hpp>
  28. namespace ranges
  29. {
  30. /// \addtogroup group-algorithms
  31. /// @{
  32. RANGES_BEGIN_NIEBLOID(binary_search)
  33. /// \brief function template \c binary_search
  34. ///
  35. /// range-based version of the \c binary_search std algorithm
  36. ///
  37. /// \pre `Rng` is a model of the `Range` concept
  38. template<typename I,
  39. typename S,
  40. typename V,
  41. typename C = less,
  42. typename P = identity>
  43. auto RANGES_FUN_NIEBLOID(binary_search)(
  44. I first, S last, V const & val, C pred = C{}, P proj = P{})
  45. ->CPP_ret(bool)( //
  46. requires forward_iterator<I> && sentinel_for<S, I> &&
  47. indirect_strict_weak_order<C, V const *, projected<I, P>>)
  48. {
  49. first =
  50. lower_bound(std::move(first), last, val, std::ref(pred), std::ref(proj));
  51. return first != last && !invoke(pred, val, invoke(proj, *first));
  52. }
  53. /// \overload
  54. template<typename Rng, typename V, typename C = less, typename P = identity>
  55. auto RANGES_FUN_NIEBLOID(binary_search)(
  56. Rng && rng, V const & val, C pred = C{}, P proj = P{}) //
  57. ->CPP_ret(bool)( //
  58. requires forward_range<Rng> &&
  59. indirect_strict_weak_order<C, V const *, projected<iterator_t<Rng>, P>>)
  60. {
  61. static_assert(!is_infinite<Rng>::value,
  62. "Trying to binary search an infinite range");
  63. return (*this)(begin(rng), end(rng), val, std::move(pred), std::move(proj));
  64. }
  65. RANGES_END_NIEBLOID(binary_search)
  66. namespace cpp20
  67. {
  68. using ranges::binary_search;
  69. }
  70. /// @}
  71. } // namespace ranges
  72. #endif // include guard