reduce.hpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. Copyright (c) Marshall Clow 2017.
  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 reduce.hpp
  7. /// \brief Combine the elements of a sequence into a single value
  8. /// \author Marshall Clow
  9. #ifndef BOOST_ALGORITHM_REDUCE_HPP
  10. #define BOOST_ALGORITHM_REDUCE_HPP
  11. #include <functional> // for std::plus
  12. #include <iterator> // for std::iterator_traits
  13. #include <boost/config.hpp>
  14. #include <boost/range/begin.hpp>
  15. #include <boost/range/end.hpp>
  16. #include <boost/range/value_type.hpp>
  17. namespace boost { namespace algorithm {
  18. template<class InputIterator, class T, class BinaryOperation>
  19. T reduce(InputIterator first, InputIterator last, T init, BinaryOperation bOp)
  20. {
  21. ;
  22. for (; first != last; ++first)
  23. init = bOp(init, *first);
  24. return init;
  25. }
  26. template<class InputIterator, class T>
  27. T reduce(InputIterator first, InputIterator last, T init)
  28. {
  29. typedef typename std::iterator_traits<InputIterator>::value_type VT;
  30. return boost::algorithm::reduce(first, last, init, std::plus<VT>());
  31. }
  32. template<class InputIterator>
  33. typename std::iterator_traits<InputIterator>::value_type
  34. reduce(InputIterator first, InputIterator last)
  35. {
  36. return boost::algorithm::reduce(first, last,
  37. typename std::iterator_traits<InputIterator>::value_type());
  38. }
  39. template<class Range>
  40. typename boost::range_value<Range>::type
  41. reduce(const Range &r)
  42. {
  43. return boost::algorithm::reduce(boost::begin(r), boost::end(r));
  44. }
  45. // Not sure that this won't be ambiguous (1)
  46. template<class Range, class T>
  47. T reduce(const Range &r, T init)
  48. {
  49. return boost::algorithm::reduce(boost::begin (r), boost::end (r), init);
  50. }
  51. // Not sure that this won't be ambiguous (2)
  52. template<class Range, class T, class BinaryOperation>
  53. T reduce(const Range &r, T init, BinaryOperation bOp)
  54. {
  55. return boost::algorithm::reduce(boost::begin(r), boost::end(r), init, bOp);
  56. }
  57. }} // namespace boost and algorithm
  58. #endif // BOOST_ALGORITHM_REDUCE_HPP