inclusive_scan.hpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 transform_reduce.hpp
  7. /// \brief Combine the (transformed) elements of a sequence (or two) into a single value.
  8. /// \author Marshall Clow
  9. #ifndef BOOST_ALGORITHM_TRANSFORM_REDUCE_HPP
  10. #define BOOST_ALGORITHM_TRANSFORM_REDUCE_HPP
  11. #include <functional> // for std::plus
  12. #include <iterator> // for std::iterator_traits
  13. #include <boost/range/begin.hpp>
  14. #include <boost/range/end.hpp>
  15. #include <boost/range/value_type.hpp>
  16. namespace boost { namespace algorithm {
  17. template<class InputIterator, class OutputIterator, class T, class BinaryOperation>
  18. OutputIterator inclusive_scan(InputIterator first, InputIterator last,
  19. OutputIterator result, BinaryOperation bOp, T init)
  20. {
  21. for (; first != last; ++first, (void) ++result) {
  22. init = bOp(init, *first);
  23. *result = init;
  24. }
  25. return result;
  26. }
  27. template<class InputIterator, class OutputIterator, class BinaryOperation>
  28. OutputIterator inclusive_scan(InputIterator first, InputIterator last,
  29. OutputIterator result, BinaryOperation bOp)
  30. {
  31. if (first != last) {
  32. typename std::iterator_traits<InputIterator>::value_type init = *first;
  33. *result++ = init;
  34. if (++first != last)
  35. return boost::algorithm::inclusive_scan(first, last, result, bOp, init);
  36. }
  37. return result;
  38. }
  39. template<class InputIterator, class OutputIterator>
  40. OutputIterator inclusive_scan(InputIterator first, InputIterator last,
  41. OutputIterator result)
  42. {
  43. typedef typename std::iterator_traits<InputIterator>::value_type VT;
  44. return boost::algorithm::inclusive_scan(first, last, result, std::plus<VT>());
  45. }
  46. }} // namespace boost and algorithm
  47. #endif // BOOST_ALGORITHM_TRANSFORM_REDUCE_HPP