2 Copyright (c) Marshall Clow 2017.
4 Distributed under the Boost Software License, Version 1.0. (See accompanying
5 file LICENSE10.txt or copy at http://www.boost.org/LICENSE10.txt)
9 /// \brief Combine the elements of a sequence into a single value
10 /// \author Marshall Clow
12 #ifndef BOOST_ALGORITHM_REDUCE_HPP
13 #define BOOST_ALGORITHM_REDUCE_HPP
15 #include <functional> // for std::plus
16 #include <iterator> // for std::iterator_traits
18 #include <boost/range/begin.hpp>
19 #include <boost/range/end.hpp>
20 #include <boost/range/value_type.hpp>
22 namespace boost { namespace algorithm {
24 template<class InputIterator, class T, class BinaryOperation>
25 T reduce(InputIterator first, InputIterator last, T init, BinaryOperation bOp)
28 for (; first != last; ++first)
29 init = bOp(init, *first);
33 template<class InputIterator, class T>
34 T reduce(InputIterator first, InputIterator last, T init)
36 typedef typename std::iterator_traits<InputIterator>::value_type VT;
37 return reduce(first, last, init, std::plus<VT>());
40 template<class InputIterator>
41 typename std::iterator_traits<InputIterator>::value_type
42 reduce(InputIterator first, InputIterator last)
44 return reduce(first, last,
45 typename std::iterator_traits<InputIterator>::value_type());
49 typename boost::range_value<Range>::type
50 reduce(const Range &r)
52 return reduce(boost::begin(r), boost::end(r));
55 // Not sure that this won't be ambiguous (1)
56 template<class Range, class T>
57 T reduce(const Range &r, T init)
59 return reduce(boost::begin (r), boost::end (r), init);
63 // Not sure that this won't be ambiguous (2)
64 template<class Range, class T, class BinaryOperation>
65 T reduce(const Range &r, T init, BinaryOperation bOp)
67 return reduce(boost::begin(r), boost::end(r), init, bOp);
70 }} // namespace boost and algorithm
72 #endif // BOOST_ALGORITHM_REDUCE_HPP