adjacent_difference.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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_ADJACENT_DIFFERENCE_H
  10. #define _LIBCPP___NUMERIC_ADJACENT_DIFFERENCE_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_BEGIN_NAMESPACE_STD
  18. template <class _InputIterator, class _OutputIterator>
  19. _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_SINCE_CXX20
  20. _OutputIterator
  21. adjacent_difference(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
  22. {
  23. if (__first != __last)
  24. {
  25. typename iterator_traits<_InputIterator>::value_type __acc(*__first);
  26. *__result = __acc;
  27. for (++__first, (void) ++__result; __first != __last; ++__first, (void) ++__result)
  28. {
  29. typename iterator_traits<_InputIterator>::value_type __val(*__first);
  30. #if _LIBCPP_STD_VER > 17
  31. *__result = __val - _VSTD::move(__acc);
  32. #else
  33. *__result = __val - __acc;
  34. #endif
  35. __acc = _VSTD::move(__val);
  36. }
  37. }
  38. return __result;
  39. }
  40. template <class _InputIterator, class _OutputIterator, class _BinaryOperation>
  41. _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_SINCE_CXX20
  42. _OutputIterator
  43. adjacent_difference(_InputIterator __first, _InputIterator __last, _OutputIterator __result,
  44. _BinaryOperation __binary_op)
  45. {
  46. if (__first != __last)
  47. {
  48. typename iterator_traits<_InputIterator>::value_type __acc(*__first);
  49. *__result = __acc;
  50. for (++__first, (void) ++__result; __first != __last; ++__first, (void) ++__result)
  51. {
  52. typename iterator_traits<_InputIterator>::value_type __val(*__first);
  53. #if _LIBCPP_STD_VER > 17
  54. *__result = __binary_op(__val, _VSTD::move(__acc));
  55. #else
  56. *__result = __binary_op(__val, __acc);
  57. #endif
  58. __acc = _VSTD::move(__val);
  59. }
  60. }
  61. return __result;
  62. }
  63. _LIBCPP_END_NAMESPACE_STD
  64. #endif // _LIBCPP___NUMERIC_ADJACENT_DIFFERENCE_H