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