transform_reduce.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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_TRANSFORM_REDUCE_H
  10. #define _LIBCPP___NUMERIC_TRANSFORM_REDUCE_H
  11. #include <__config>
  12. #include <__functional/operations.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. #if _LIBCPP_STD_VER >= 17
  21. template <class _InputIterator, class _Tp, class _BinaryOp, class _UnaryOp>
  22. _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 _Tp
  23. transform_reduce(_InputIterator __first, _InputIterator __last, _Tp __init, _BinaryOp __b, _UnaryOp __u) {
  24. for (; __first != __last; ++__first)
  25. __init = __b(std::move(__init), __u(*__first));
  26. return __init;
  27. }
  28. template <class _InputIterator1, class _InputIterator2, class _Tp, class _BinaryOp1, class _BinaryOp2>
  29. _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 _Tp transform_reduce(
  30. _InputIterator1 __first1,
  31. _InputIterator1 __last1,
  32. _InputIterator2 __first2,
  33. _Tp __init,
  34. _BinaryOp1 __b1,
  35. _BinaryOp2 __b2) {
  36. for (; __first1 != __last1; ++__first1, (void)++__first2)
  37. __init = __b1(std::move(__init), __b2(*__first1, *__first2));
  38. return __init;
  39. }
  40. template <class _InputIterator1, class _InputIterator2, class _Tp>
  41. _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 _Tp
  42. transform_reduce(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _Tp __init) {
  43. return std::transform_reduce(__first1, __last1, __first2, std::move(__init), std::plus<>(), std::multiplies<>());
  44. }
  45. #endif
  46. _LIBCPP_END_NAMESPACE_STD
  47. _LIBCPP_POP_MACROS
  48. #endif // _LIBCPP___NUMERIC_TRANSFORM_REDUCE_H