partial_sum.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // -*- C++ -*-
  2. //===----------------------------------------------------------------------===//
  3. //
  4. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  5. // See https://llvm.org/LICENSE.txt for license information.
  6. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #ifndef _LIBCPP___NUMERIC_PARTIAL_SUM_H
  10. #define _LIBCPP___NUMERIC_PARTIAL_SUM_H
  11. #include <__config>
  12. #include <__iterator/iterator_traits.h>
  13. #include <__utility/move.h>
  14. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  15. # pragma GCC system_header
  16. #endif
  17. _LIBCPP_PUSH_MACROS
  18. #include <__undef_macros>
  19. _LIBCPP_BEGIN_NAMESPACE_STD
  20. template <class _InputIterator, class _OutputIterator>
  21. _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_SINCE_CXX20
  22. _OutputIterator
  23. partial_sum(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
  24. {
  25. if (__first != __last)
  26. {
  27. typename iterator_traits<_InputIterator>::value_type __t(*__first);
  28. *__result = __t;
  29. for (++__first, (void) ++__result; __first != __last; ++__first, (void) ++__result)
  30. {
  31. #if _LIBCPP_STD_VER >= 20
  32. __t = _VSTD::move(__t) + *__first;
  33. #else
  34. __t = __t + *__first;
  35. #endif
  36. *__result = __t;
  37. }
  38. }
  39. return __result;
  40. }
  41. template <class _InputIterator, class _OutputIterator, class _BinaryOperation>
  42. _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_SINCE_CXX20
  43. _OutputIterator
  44. partial_sum(_InputIterator __first, _InputIterator __last, _OutputIterator __result,
  45. _BinaryOperation __binary_op)
  46. {
  47. if (__first != __last)
  48. {
  49. typename iterator_traits<_InputIterator>::value_type __t(*__first);
  50. *__result = __t;
  51. for (++__first, (void) ++__result; __first != __last; ++__first, (void) ++__result)
  52. {
  53. #if _LIBCPP_STD_VER >= 20
  54. __t = __binary_op(_VSTD::move(__t), *__first);
  55. #else
  56. __t = __binary_op(__t, *__first);
  57. #endif
  58. *__result = __t;
  59. }
  60. }
  61. return __result;
  62. }
  63. _LIBCPP_END_NAMESPACE_STD
  64. _LIBCPP_POP_MACROS
  65. #endif // _LIBCPP___NUMERIC_PARTIAL_SUM_H