1 /*
2    Copyright (c) Marshall Clow 2017.
3 
4    Distributed under the Boost Software License, Version 1.0. (See accompanying
5    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6 */
7 
8 /// \file  reduce.hpp
9 /// \brief Combine the elements of a sequence into a single value
10 /// \author Marshall Clow
11 
12 #ifndef BOOST_ALGORITHM_REDUCE_HPP
13 #define BOOST_ALGORITHM_REDUCE_HPP
14 
15 #include <functional>     // for std::plus
16 #include <iterator>       // for std::iterator_traits
17 
18 #include <boost/config.hpp>
19 #include <boost/range/begin.hpp>
20 #include <boost/range/end.hpp>
21 #include <boost/range/value_type.hpp>
22 
23 namespace boost { namespace algorithm {
24 
25 template<class InputIterator, class T, class BinaryOperation>
26 T reduce(InputIterator first, InputIterator last, T init, BinaryOperation bOp)
27 {
28     ;
29     for (; first != last; ++first)
30         init = bOp(init, *first);
31     return init;
32 }
33 
34 template<class InputIterator, class T>
reduce(InputIterator first,InputIterator last,T init)35 T reduce(InputIterator first, InputIterator last, T init)
36 {
37 	typedef typename std::iterator_traits<InputIterator>::value_type VT;
38     return boost::algorithm::reduce(first, last, init, std::plus<VT>());
39 }
40 
41 template<class InputIterator>
42 typename std::iterator_traits<InputIterator>::value_type
reduce(InputIterator first,InputIterator last)43 reduce(InputIterator first, InputIterator last)
44 {
45     return boost::algorithm::reduce(first, last,
46        typename std::iterator_traits<InputIterator>::value_type());
47 }
48 
49 template<class Range>
50 typename boost::range_value<Range>::type
reduce(const Range & r)51 reduce(const Range &r)
52 {
53     return boost::algorithm::reduce(boost::begin(r), boost::end(r));
54 }
55 
56 //	Not sure that this won't be ambiguous (1)
57 template<class Range, class T>
reduce(const Range & r,T init)58 T reduce(const Range &r, T init)
59 {
60     return boost::algorithm::reduce(boost::begin (r), boost::end (r), init);
61 }
62 
63 
64 //	Not sure that this won't be ambiguous (2)
65 template<class Range, class T, class BinaryOperation>
66 T reduce(const Range &r, T init, BinaryOperation bOp)
67 {
68     return boost::algorithm::reduce(boost::begin(r), boost::end(r), init, bOp);
69 }
70 
71 }} // namespace boost and algorithm
72 
73 #endif // BOOST_ALGORITHM_REDUCE_HPP
74