xref: /llvm-project/libcxx/include/__algorithm/push_heap.h (revision 7ed7d4ccb8991e2b5b95334b508f8cec2faee737)
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 
9 #ifndef _LIBCPP___ALGORITHM_PUSH_HEAP_H
10 #define _LIBCPP___ALGORITHM_PUSH_HEAP_H
11 
12 #include <__config>
13 #include <__algorithm/comp_ref_type.h>
14 #include <__iterator/iterator_traits.h>
15 #include <type_traits>
16 
17 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
18 #pragma GCC system_header
19 #endif
20 
21 _LIBCPP_PUSH_MACROS
22 #include <__undef_macros>
23 
24 _LIBCPP_BEGIN_NAMESPACE_STD
25 
26 template <class _Compare, class _RandomAccessIterator>
27 _LIBCPP_CONSTEXPR_AFTER_CXX11 void
28 __sift_up(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp,
29           typename iterator_traits<_RandomAccessIterator>::difference_type __len)
30 {
31     typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
32     if (__len > 1)
33     {
34         __len = (__len - 2) / 2;
35         _RandomAccessIterator __ptr = __first + __len;
36         if (__comp(*__ptr, *--__last))
37         {
38             value_type __t(_VSTD::move(*__last));
39             do
40             {
41                 *__last = _VSTD::move(*__ptr);
42                 __last = __ptr;
43                 if (__len == 0)
44                     break;
45                 __len = (__len - 1) / 2;
46                 __ptr = __first + __len;
47             } while (__comp(*__ptr, __t));
48             *__last = _VSTD::move(__t);
49         }
50     }
51 }
52 
53 template <class _RandomAccessIterator, class _Compare>
54 inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
55 void
56 push_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
57 {
58     typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
59     _VSTD::__sift_up<_Comp_ref>(__first, __last, __comp, __last - __first);
60 }
61 
62 template <class _RandomAccessIterator>
63 inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
64 void
65 push_heap(_RandomAccessIterator __first, _RandomAccessIterator __last)
66 {
67     _VSTD::push_heap(__first, __last, __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
68 }
69 
70 _LIBCPP_END_NAMESPACE_STD
71 
72 _LIBCPP_POP_MACROS
73 
74 #endif // _LIBCPP___ALGORITHM_PUSH_HEAP_H
75