make_heap.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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_MAKE_HEAP_H
  9. #define _LIBCPP___ALGORITHM_MAKE_HEAP_H
  10. #include <__algorithm/comp.h>
  11. #include <__algorithm/comp_ref_type.h>
  12. #include <__algorithm/sift_down.h>
  13. #include <__config>
  14. #include <__iterator/iterator_traits.h>
  15. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  16. # pragma GCC system_header
  17. #endif
  18. _LIBCPP_BEGIN_NAMESPACE_STD
  19. template <class _Compare, class _RandomAccessIterator>
  20. _LIBCPP_CONSTEXPR_AFTER_CXX11 void
  21. __make_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
  22. {
  23. typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
  24. difference_type __n = __last - __first;
  25. if (__n > 1)
  26. {
  27. // start from the first parent, there is no need to consider children
  28. for (difference_type __start = (__n - 2) / 2; __start >= 0; --__start)
  29. {
  30. _VSTD::__sift_down<_Compare>(__first, __comp, __n, __first + __start);
  31. }
  32. }
  33. }
  34. template <class _RandomAccessIterator, class _Compare>
  35. inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
  36. void
  37. make_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
  38. {
  39. typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
  40. _VSTD::__make_heap<_Comp_ref>(__first, __last, __comp);
  41. }
  42. template <class _RandomAccessIterator>
  43. inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
  44. void
  45. make_heap(_RandomAccessIterator __first, _RandomAccessIterator __last)
  46. {
  47. _VSTD::make_heap(__first, __last, __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
  48. }
  49. _LIBCPP_END_NAMESPACE_STD
  50. #endif // _LIBCPP___ALGORITHM_MAKE_HEAP_H