partition_point.hpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 <iterator> // for std::distance, advance
  12. #include <boost/config.hpp>
  13. #include <boost/range/begin.hpp>
  14. #include <boost/range/end.hpp>
  15. namespace boost { namespace algorithm {
  16. /// \fn partition_point ( ForwardIterator first, ForwardIterator last, Predicate p )
  17. /// \brief Given a partitioned range, returns the partition point, i.e, the first element
  18. /// that does not satisfy p
  19. ///
  20. /// \param first The start of the input sequence
  21. /// \param last One past the end of the input sequence
  22. /// \param p The predicate to test the values with
  23. /// \note This function is part of the C++2011 standard library.
  24. template <typename ForwardIterator, typename Predicate>
  25. ForwardIterator partition_point ( ForwardIterator first, ForwardIterator last, Predicate p )
  26. {
  27. std::size_t dist = std::distance ( first, last );
  28. while ( first != last ) {
  29. std::size_t d2 = dist / 2;
  30. ForwardIterator ret_val = first;
  31. std::advance (ret_val, d2);
  32. if (p (*ret_val)) {
  33. first = ++ret_val;
  34. dist -= d2 + 1;
  35. }
  36. else {
  37. last = ret_val;
  38. dist = d2;
  39. }
  40. }
  41. return first;
  42. }
  43. /// \fn partition_point ( Range &r, Predicate p )
  44. /// \brief Given a partitioned range, returns the partition point
  45. ///
  46. /// \param r The input range
  47. /// \param p The predicate to test the values with
  48. ///
  49. template <typename Range, typename Predicate>
  50. typename boost::range_iterator<Range>::type partition_point ( Range &r, Predicate p )
  51. {
  52. return boost::algorithm::partition_point (boost::begin(r), boost::end(r), p);
  53. }
  54. }}
  55. #endif // BOOST_ALGORITHM_PARTITION_POINT_HPP