reverse.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. //===----------------------------------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #ifndef _LIBCPP___ALGORITHM_REVERSE_H
  9. #define _LIBCPP___ALGORITHM_REVERSE_H
  10. #include <__algorithm/iter_swap.h>
  11. #include <__algorithm/iterator_operations.h>
  12. #include <__config>
  13. #include <__iterator/iterator_traits.h>
  14. #include <__utility/move.h>
  15. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  16. # pragma GCC system_header
  17. #endif
  18. _LIBCPP_PUSH_MACROS
  19. #include <__undef_macros>
  20. _LIBCPP_BEGIN_NAMESPACE_STD
  21. template <class _AlgPolicy, class _BidirectionalIterator>
  22. inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 void
  23. __reverse_impl(_BidirectionalIterator __first, _BidirectionalIterator __last, bidirectional_iterator_tag) {
  24. while (__first != __last) {
  25. if (__first == --__last)
  26. break;
  27. _IterOps<_AlgPolicy>::iter_swap(__first, __last);
  28. ++__first;
  29. }
  30. }
  31. template <class _AlgPolicy, class _RandomAccessIterator>
  32. inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 void
  33. __reverse_impl(_RandomAccessIterator __first, _RandomAccessIterator __last, random_access_iterator_tag) {
  34. if (__first != __last)
  35. for (; __first < --__last; ++__first)
  36. _IterOps<_AlgPolicy>::iter_swap(__first, __last);
  37. }
  38. template <class _AlgPolicy, class _BidirectionalIterator, class _Sentinel>
  39. _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 void __reverse(_BidirectionalIterator __first, _Sentinel __last) {
  40. using _IterCategory = typename _IterOps<_AlgPolicy>::template __iterator_category<_BidirectionalIterator>;
  41. std::__reverse_impl<_AlgPolicy>(std::move(__first), std::move(__last), _IterCategory());
  42. }
  43. template <class _BidirectionalIterator>
  44. inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 void
  45. reverse(_BidirectionalIterator __first, _BidirectionalIterator __last) {
  46. std::__reverse<_ClassicAlgPolicy>(std::move(__first), std::move(__last));
  47. }
  48. _LIBCPP_END_NAMESPACE_STD
  49. _LIBCPP_POP_MACROS
  50. #endif // _LIBCPP___ALGORITHM_REVERSE_H