pop_heap.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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_POP_HEAP_H
  9. #define _LIBCPP___ALGORITHM_POP_HEAP_H
  10. #include <__algorithm/comp.h>
  11. #include <__algorithm/comp_ref_type.h>
  12. #include <__algorithm/push_heap.h>
  13. #include <__algorithm/sift_down.h>
  14. #include <__assert>
  15. #include <__config>
  16. #include <__iterator/iterator_traits.h>
  17. #include <__utility/move.h>
  18. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  19. # pragma GCC system_header
  20. #endif
  21. _LIBCPP_BEGIN_NAMESPACE_STD
  22. template <class _Compare, class _RandomAccessIterator>
  23. inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX11
  24. void __pop_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare& __comp,
  25. typename iterator_traits<_RandomAccessIterator>::difference_type __len) {
  26. _LIBCPP_ASSERT(__len > 0, "The heap given to pop_heap must be non-empty");
  27. using _CompRef = typename __comp_ref_type<_Compare>::type;
  28. _CompRef __comp_ref = __comp;
  29. using value_type = typename iterator_traits<_RandomAccessIterator>::value_type;
  30. if (__len > 1) {
  31. value_type __top = std::move(*__first); // create a hole at __first
  32. _RandomAccessIterator __hole = std::__floyd_sift_down<_CompRef>(__first, __comp_ref, __len);
  33. --__last;
  34. if (__hole == __last) {
  35. *__hole = std::move(__top);
  36. } else {
  37. *__hole = std::move(*__last);
  38. ++__hole;
  39. *__last = std::move(__top);
  40. std::__sift_up<_CompRef>(__first, __hole, __comp_ref, __hole - __first);
  41. }
  42. }
  43. }
  44. template <class _RandomAccessIterator, class _Compare>
  45. inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17
  46. void pop_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) {
  47. typename iterator_traits<_RandomAccessIterator>::difference_type __len = __last - __first;
  48. std::__pop_heap(std::move(__first), std::move(__last), __comp, __len);
  49. }
  50. template <class _RandomAccessIterator>
  51. inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17
  52. void pop_heap(_RandomAccessIterator __first, _RandomAccessIterator __last) {
  53. std::pop_heap(std::move(__first), std::move(__last),
  54. __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
  55. }
  56. _LIBCPP_END_NAMESPACE_STD
  57. #endif // _LIBCPP___ALGORITHM_POP_HEAP_H