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