partition_point.hpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. Copyright (c) Marshall Clow 2011-2012.
  3. Distributed under the Boost Software License, Version 1.0. (See accompanying
  4. file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  5. */
  6. /// \file partition_point.hpp
  7. /// \brief Find the partition point in a sequence
  8. /// \author Marshall Clow
  9. #ifndef BOOST_ALGORITHM_PARTITION_POINT_HPP
  10. #define BOOST_ALGORITHM_PARTITION_POINT_HPP
  11. #include <algorithm> // for std::partition_point, if available
  12. #include <boost/range/begin.hpp>
  13. #include <boost/range/end.hpp>
  14. namespace boost { namespace algorithm {
  15. #if __cplusplus >= 201103L
  16. // Use the C++11 versions of partition_point if it is available
  17. using std::partition_point; // Section 25.3.13
  18. #else
  19. /// \fn partition_point ( ForwardIterator first, ForwardIterator last, Predicate p )
  20. /// \brief Given a partitioned range, returns the partition point, i.e, the first element
  21. /// that does not satisfy p
  22. ///
  23. /// \param first The start of the input sequence
  24. /// \param last One past the end of the input sequence
  25. /// \param p The predicate to test the values with
  26. /// \note This function is part of the C++2011 standard library.
  27. /// We will use the standard one if it is available,
  28. /// otherwise we have our own implementation.
  29. template <typename ForwardIterator, typename Predicate>
  30. ForwardIterator partition_point ( ForwardIterator first, ForwardIterator last, Predicate p )
  31. {
  32. std::size_t dist = std::distance ( first, last );
  33. while ( first != last ) {
  34. std::size_t d2 = dist / 2;
  35. ForwardIterator ret_val = first;
  36. std::advance (ret_val, d2);
  37. if (p (*ret_val)) {
  38. first = ++ret_val;
  39. dist -= d2 + 1;
  40. }
  41. else {
  42. last = ret_val;
  43. dist = d2;
  44. }
  45. }
  46. return first;
  47. }
  48. #endif
  49. /// \fn partition_point ( Range &r, Predicate p )
  50. /// \brief Given a partitioned range, returns the partition point
  51. ///
  52. /// \param r The input range
  53. /// \param p The predicate to test the values with
  54. ///
  55. template <typename Range, typename Predicate>
  56. typename boost::range_iterator<Range> partition_point ( Range &r, Predicate p )
  57. {
  58. return boost::algorithm::partition_point (boost::begin(r), boost::end(r), p);
  59. }
  60. }}
  61. #endif // BOOST_ALGORITHM_PARTITION_POINT_HPP