73 lines · c
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-exception6//7//===----------------------------------------------------------------------===//8 9#ifndef _LIBCPP___ALGORITHM_MAKE_HEAP_H10#define _LIBCPP___ALGORITHM_MAKE_HEAP_H11 12#include <__algorithm/comp.h>13#include <__algorithm/comp_ref_type.h>14#include <__algorithm/iterator_operations.h>15#include <__algorithm/push_heap.h>16#include <__algorithm/sift_down.h>17#include <__config>18#include <__iterator/iterator_traits.h>19#include <__type_traits/is_arithmetic.h>20#include <__utility/move.h>21 22#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)23# pragma GCC system_header24#endif25 26_LIBCPP_PUSH_MACROS27#include <__undef_macros>28 29_LIBCPP_BEGIN_NAMESPACE_STD30 31template <class _AlgPolicy, class _Compare, class _RandomAccessIterator>32inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 void33__make_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare&& __comp) {34 __comp_ref_type<_Compare> __comp_ref = __comp;35 36 using __diff_t = __iterator_difference_type<_RandomAccessIterator>;37 const __diff_t __n = __last - __first;38 39 const bool __assume_both_children = is_arithmetic<__iterator_value_type<_RandomAccessIterator> >::value;40 41 // While it would be correct to always assume we have both children, in practice we observed this to be a performance42 // improvement only for arithmetic types.43 const __diff_t __sift_down_n = __assume_both_children ? ((__n & 1) ? __n : __n - 1) : __n;44 45 if (__n > 1) {46 // start from the first parent, there is no need to consider children47 48 for (__diff_t __start = (__sift_down_n - 2) / 2; __start >= 0; --__start) {49 std::__sift_down<_AlgPolicy, __assume_both_children>(__first, __comp_ref, __sift_down_n, __start);50 }51 if _LIBCPP_CONSTEXPR (__assume_both_children)52 std::__sift_up<_AlgPolicy>(__first, __last, __comp, __n);53 }54}55 56template <class _RandomAccessIterator, class _Compare>57inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 void58make_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) {59 std::__make_heap<_ClassicAlgPolicy>(std::move(__first), std::move(__last), __comp);60}61 62template <class _RandomAccessIterator>63inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 void64make_heap(_RandomAccessIterator __first, _RandomAccessIterator __last) {65 std::make_heap(std::move(__first), std::move(__last), __less<>());66}67 68_LIBCPP_END_NAMESPACE_STD69 70_LIBCPP_POP_MACROS71 72#endif // _LIBCPP___ALGORITHM_MAKE_HEAP_H73