transform_reduce.hpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 InputIterator1, class InputIterator2, class T,
  18. class BinaryOperation1, class BinaryOperation2>
  19. T transform_reduce(InputIterator1 first1, InputIterator1 last1,
  20. InputIterator2 first2, T init,
  21. BinaryOperation1 bOp1, BinaryOperation2 bOp2)
  22. {
  23. for (; first1 != last1; ++first1, (void) ++first2)
  24. init = bOp1(init, bOp2(*first1, *first2));
  25. return init;
  26. }
  27. template<class InputIterator, class T,
  28. class BinaryOperation, class UnaryOperation>
  29. T transform_reduce(InputIterator first, InputIterator last,
  30. T init, BinaryOperation bOp, UnaryOperation uOp)
  31. {
  32. for (; first != last; ++first)
  33. init = bOp(init, uOp(*first));
  34. return init;
  35. }
  36. template<class InputIterator1, class InputIterator2, class T>
  37. T transform_reduce(InputIterator1 first1, InputIterator1 last1,
  38. InputIterator2 first2, T init)
  39. {
  40. return boost::algorithm::transform_reduce(first1, last1, first2, init,
  41. std::plus<T>(), std::multiplies<T>());
  42. }
  43. }} // namespace boost and algorithm
  44. #endif // BOOST_ALGORITHM_TRANSFORM_REDUCE_HPP