accumulate.hpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /// \file
  2. // Range v3 library
  3. //
  4. // Copyright Eric Niebler 2013-present
  5. //
  6. // Use, modification and distribution is subject to the
  7. // Boost Software License, Version 1.0. (See accompanying
  8. // file LICENSE_1_0.txt or copy at
  9. // http://www.boost.org/LICENSE_1_0.txt)
  10. //
  11. // Project home: https://github.com/ericniebler/range-v3
  12. //
  13. #ifndef RANGES_V3_NUMERIC_ACCUMULATE_HPP
  14. #define RANGES_V3_NUMERIC_ACCUMULATE_HPP
  15. #include <meta/meta.hpp>
  16. #include <range/v3/functional/arithmetic.hpp>
  17. #include <range/v3/functional/identity.hpp>
  18. #include <range/v3/functional/invoke.hpp>
  19. #include <range/v3/iterator/concepts.hpp>
  20. #include <range/v3/iterator/traits.hpp>
  21. #include <range/v3/range/access.hpp>
  22. #include <range/v3/range/concepts.hpp>
  23. #include <range/v3/range/traits.hpp>
  24. #include <range/v3/utility/static_const.hpp>
  25. #include <range/v3/detail/prologue.hpp>
  26. namespace ranges
  27. {
  28. /// \addtogroup group-numerics
  29. /// @{
  30. struct accumulate_fn
  31. {
  32. template(typename I, typename S, typename T, typename Op = plus,
  33. typename P = identity)(
  34. requires sentinel_for<S, I> AND input_iterator<I> AND
  35. indirectly_binary_invocable_<Op, T *, projected<I, P>> AND
  36. assignable_from<T &, indirect_result_t<Op &, T *, projected<I, P>>>)
  37. T operator()(I first, S last, T init, Op op = Op{},
  38. P proj = P{}) const
  39. {
  40. for(; first != last; ++first)
  41. init = invoke(op, init, invoke(proj, *first));
  42. return init;
  43. }
  44. template(typename Rng, typename T, typename Op = plus, typename P = identity)(
  45. requires input_range<Rng> AND
  46. indirectly_binary_invocable_<Op, T *, projected<iterator_t<Rng>, P>> AND
  47. assignable_from<
  48. T &, indirect_result_t<Op &, T *, projected<iterator_t<Rng>, P>>>)
  49. T operator()(Rng && rng, T init, Op op = Op{}, P proj = P{}) const
  50. {
  51. return (*this)(
  52. begin(rng), end(rng), std::move(init), std::move(op), std::move(proj));
  53. }
  54. };
  55. RANGES_INLINE_VARIABLE(accumulate_fn, accumulate)
  56. /// @}
  57. } // namespace ranges
  58. #include <range/v3/detail/epilogue.hpp>
  59. #endif