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_INCLUSIVE_SCAN_HPP
  10. #define BOOST_ALGORITHM_INCLUSIVE_SCAN_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 OutputIterator, class T, class BinaryOperation>
  19. OutputIterator inclusive_scan(InputIterator first, InputIterator last,
  20. OutputIterator result, BinaryOperation bOp, T init)
  21. {
  22. for (; first != last; ++first, (void) ++result) {
  23. init = bOp(init, *first);
  24. *result = init;
  25. }
  26. return result;
  27. }
  28. template<class InputIterator, class OutputIterator, class BinaryOperation>
  29. OutputIterator inclusive_scan(InputIterator first, InputIterator last,
  30. OutputIterator result, BinaryOperation bOp)
  31. {
  32. if (first != last) {
  33. typename std::iterator_traits<InputIterator>::value_type init = *first;
  34. *result++ = init;
  35. if (++first != last)
  36. return boost::algorithm::inclusive_scan(first, last, result, bOp, init);
  37. }
  38. return result;
  39. }
  40. template<class InputIterator, class OutputIterator>
  41. OutputIterator inclusive_scan(InputIterator first, InputIterator last,
  42. OutputIterator result)
  43. {
  44. typedef typename std::iterator_traits<InputIterator>::value_type VT;
  45. return boost::algorithm::inclusive_scan(first, last, result, std::plus<VT>());
  46. }
  47. }} // namespace boost and algorithm
  48. #endif // BOOST_ALGORITHM_INCLUSIVE_SCAN_HPP