libstdc++
stl_heap.h
Go to the documentation of this file.
1// Heap implementation -*- C++ -*-
2
3// Copyright (C) 2001-2025 Free Software Foundation, Inc.
4//
5// This file is part of the GNU ISO C++ Library. This library is free
6// software; you can redistribute it and/or modify it under the
7// terms of the GNU General Public License as published by the
8// Free Software Foundation; either version 3, or (at your option)
9// any later version.
10
11// This library is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// Under Section 7 of GPL version 3, you are granted additional
17// permissions described in the GCC Runtime Library Exception, version
18// 3.1, as published by the Free Software Foundation.
19
20// You should have received a copy of the GNU General Public License and
21// a copy of the GCC Runtime Library Exception along with this program;
22// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23// <http://www.gnu.org/licenses/>.
24
25/*
26 *
27 * Copyright (c) 1994
28 * Hewlett-Packard Company
29 *
30 * Permission to use, copy, modify, distribute and sell this software
31 * and its documentation for any purpose is hereby granted without fee,
32 * provided that the above copyright notice appear in all copies and
33 * that both that copyright notice and this permission notice appear
34 * in supporting documentation. Hewlett-Packard Company makes no
35 * representations about the suitability of this software for any
36 * purpose. It is provided "as is" without express or implied warranty.
37 *
38 * Copyright (c) 1997
39 * Silicon Graphics Computer Systems, Inc.
40 *
41 * Permission to use, copy, modify, distribute and sell this software
42 * and its documentation for any purpose is hereby granted without fee,
43 * provided that the above copyright notice appear in all copies and
44 * that both that copyright notice and this permission notice appear
45 * in supporting documentation. Silicon Graphics makes no
46 * representations about the suitability of this software for any
47 * purpose. It is provided "as is" without express or implied warranty.
48 */
49
50/** @file bits/stl_heap.h
51 * This is an internal header file, included by other library headers.
52 * Do not attempt to use it directly. @headername{queue}
53 */
54
55#ifndef _STL_HEAP_H
56#define _STL_HEAP_H 1
57
58#include <debug/debug.h>
59#include <bits/move.h>
60#include <bits/predefined_ops.h>
62
63namespace std _GLIBCXX_VISIBILITY(default)
64{
65_GLIBCXX_BEGIN_NAMESPACE_VERSION
66
67 /**
68 * @defgroup heap_algorithms Heap
69 * @ingroup sorting_algorithms
70 */
71
72 template<typename _RandomAccessIterator, typename _Distance,
73 typename _Compare>
74 _GLIBCXX20_CONSTEXPR
75 _Distance
76 __is_heap_until(_RandomAccessIterator __first, _Distance __n,
77 _Compare& __comp)
78 {
79#if __cplusplus >= 201103L
81 static_assert(is_same<typename _IterTraits::difference_type,
82 _Distance>::value,
83 "Argument 'n' must be the iterator's difference type");
84#endif
85 _Distance __parent = 0;
86 for (_Distance __child = 1; __child < __n; ++__child)
87 {
88 if (__comp(__first + __parent, __first + __child))
89 return __child;
90 if ((__child & 1) == 0)
91 ++__parent;
92 }
93 return __n;
94 }
95
96 // __is_heap, a predicate testing whether or not a range is a heap.
97 // This function is an extension, not part of the C++ standard.
98 template<typename _RandomAccessIterator, typename _Distance>
99 _GLIBCXX20_CONSTEXPR
100 inline bool
101 __is_heap(_RandomAccessIterator __first, _Distance __n)
102 {
104 __gnu_cxx::__ops::_Iter_less_iter __comp;
105 return std::__is_heap_until(__first, __d, __comp) == __n;
106 }
107
108 template<typename _RandomAccessIterator, typename _Compare,
109 typename _Distance>
110 _GLIBCXX20_CONSTEXPR
111 inline bool
112 __is_heap(_RandomAccessIterator __first, _Compare __comp, _Distance __n)
113 {
115 typedef __decltype(__comp) _Cmp;
116 __gnu_cxx::__ops::_Iter_comp_iter<_Cmp> __cmp(_GLIBCXX_MOVE(__comp));
117 return std::__is_heap_until(__first, __d, __cmp) == __n;
118 }
119
120 template<typename _RandomAccessIterator>
121 _GLIBCXX20_CONSTEXPR
122 inline bool
123 __is_heap(_RandomAccessIterator __first, _RandomAccessIterator __last)
124 { return std::__is_heap(__first, std::distance(__first, __last)); }
125
126 template<typename _RandomAccessIterator, typename _Compare>
127 _GLIBCXX20_CONSTEXPR
128 inline bool
129 __is_heap(_RandomAccessIterator __first, _RandomAccessIterator __last,
130 _Compare __comp)
131 {
132 return std::__is_heap(__first, _GLIBCXX_MOVE(__comp),
133 std::distance(__first, __last));
134 }
135
136 // Heap-manipulation functions: push_heap, pop_heap, make_heap, sort_heap,
137 // + is_heap and is_heap_until in C++0x.
138
139 template<typename _RandomAccessIterator, typename _Distance, typename _Tp,
140 typename _Compare>
141 _GLIBCXX20_CONSTEXPR
142 void
143 __push_heap(_RandomAccessIterator __first,
144 _Distance __holeIndex, _Distance __topIndex, _Tp __value,
145 _Compare& __comp)
146 {
147 _Distance __parent = (__holeIndex - 1) / 2;
148 while (__holeIndex > __topIndex && __comp(__first + __parent, __value))
149 {
150 *(__first + __holeIndex) = _GLIBCXX_MOVE(*(__first + __parent));
151 __holeIndex = __parent;
152 __parent = (__holeIndex - 1) / 2;
153 }
154 *(__first + __holeIndex) = _GLIBCXX_MOVE(__value);
155 }
156
157 /**
158 * @brief Push an element onto a heap.
159 * @param __first Start of heap.
160 * @param __last End of heap + element.
161 * @ingroup heap_algorithms
162 *
163 * This operation pushes the element at last-1 onto the valid heap
164 * over the range [__first,__last-1). After completion,
165 * [__first,__last) is a valid heap.
166 */
167 template<typename _RandomAccessIterator>
168 _GLIBCXX20_CONSTEXPR
169 inline void
170 push_heap(_RandomAccessIterator __first, _RandomAccessIterator __last)
171 {
173 _ValueType;
175 _DistanceType;
176
177 // concept requirements
178 __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept<
179 _RandomAccessIterator>)
180 __glibcxx_function_requires(_LessThanComparableConcept<_ValueType>)
181 __glibcxx_requires_valid_range(__first, __last);
182 __glibcxx_requires_irreflexive(__first, __last);
183 __glibcxx_requires_heap(__first, __last - _DistanceType(1));
184
185 __gnu_cxx::__ops::_Iter_less_val __comp;
186 _ValueType __value = _GLIBCXX_MOVE(*(__last - _DistanceType(1)));
187 std::__push_heap(__first, _DistanceType((__last - __first) - 1),
188 _DistanceType(0), _GLIBCXX_MOVE(__value), __comp);
189 }
190
191 /**
192 * @brief Push an element onto a heap using comparison functor.
193 * @param __first Start of heap.
194 * @param __last End of heap + element.
195 * @param __comp Comparison functor.
196 * @ingroup heap_algorithms
197 *
198 * This operation pushes the element at __last-1 onto the valid
199 * heap over the range [__first,__last-1). After completion,
200 * [__first,__last) is a valid heap. Compare operations are
201 * performed using comp.
202 */
203 template<typename _RandomAccessIterator, typename _Compare>
204 _GLIBCXX20_CONSTEXPR
205 inline void
206 push_heap(_RandomAccessIterator __first, _RandomAccessIterator __last,
207 _Compare __comp)
208 {
210 _ValueType;
212 _DistanceType;
213
214 // concept requirements
215 __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept<
216 _RandomAccessIterator>)
217 __glibcxx_requires_valid_range(__first, __last);
218 __glibcxx_requires_irreflexive_pred(__first, __last, __comp);
219 __glibcxx_requires_heap_pred(__first, __last - _DistanceType(1), __comp);
220
221 __decltype(__gnu_cxx::__ops::__iter_comp_val(_GLIBCXX_MOVE(__comp)))
222 __cmp(_GLIBCXX_MOVE(__comp));
223 _ValueType __value = _GLIBCXX_MOVE(*(__last - _DistanceType(1)));
224 std::__push_heap(__first, _DistanceType((__last - __first) - 1),
225 _DistanceType(0), _GLIBCXX_MOVE(__value), __cmp);
226 }
227
228 template<typename _RandomAccessIterator, typename _Distance,
229 typename _Tp, typename _Compare>
230 _GLIBCXX20_CONSTEXPR
231 void
232 __adjust_heap(_RandomAccessIterator __first, _Distance __holeIndex,
233 _Distance __len, _Tp __value, _Compare __comp)
234 {
235 const _Distance __topIndex = __holeIndex;
236 _Distance __secondChild = __holeIndex;
237 while (__secondChild < (__len - 1) / 2)
238 {
239 __secondChild = 2 * (__secondChild + 1);
240 if (__comp(__first + __secondChild,
241 __first + (__secondChild - 1)))
242 __secondChild--;
243 *(__first + __holeIndex) = _GLIBCXX_MOVE(*(__first + __secondChild));
244 __holeIndex = __secondChild;
245 }
246 if ((__len & 1) == 0 && __secondChild == (__len - 2) / 2)
247 {
248 __secondChild = 2 * (__secondChild + 1);
249 *(__first + __holeIndex) = _GLIBCXX_MOVE(*(__first
250 + (__secondChild - 1)));
251 __holeIndex = __secondChild - 1;
252 }
253 __decltype(__gnu_cxx::__ops::__iter_comp_val(_GLIBCXX_MOVE(__comp)))
254 __cmp(_GLIBCXX_MOVE(__comp));
255 std::__push_heap(__first, __holeIndex, __topIndex,
256 _GLIBCXX_MOVE(__value), __cmp);
257 }
258
259 template<typename _RandomAccessIterator, typename _Compare>
260 _GLIBCXX20_CONSTEXPR
261 inline void
262 __pop_heap(_RandomAccessIterator __first, _RandomAccessIterator __last,
263 _RandomAccessIterator __result, _Compare& __comp)
264 {
266 _ValueType;
268 _DistanceType;
269
270 _ValueType __value = _GLIBCXX_MOVE(*__result);
271 *__result = _GLIBCXX_MOVE(*__first);
272 std::__adjust_heap(__first, _DistanceType(0),
273 _DistanceType(__last - __first),
274 _GLIBCXX_MOVE(__value), __comp);
275 }
276
277 /**
278 * @brief Pop an element off a heap.
279 * @param __first Start of heap.
280 * @param __last End of heap.
281 * @pre [__first, __last) is a valid, non-empty range.
282 * @ingroup heap_algorithms
283 *
284 * This operation pops the top of the heap. The elements __first
285 * and __last-1 are swapped and [__first,__last-1) is made into a
286 * heap.
287 */
288 template<typename _RandomAccessIterator>
289 _GLIBCXX20_CONSTEXPR
290 inline void
291 pop_heap(_RandomAccessIterator __first, _RandomAccessIterator __last)
292 {
293 // concept requirements
294 __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept<
295 _RandomAccessIterator>)
296 __glibcxx_function_requires(_LessThanComparableConcept<
298 __glibcxx_requires_non_empty_range(__first, __last);
299 __glibcxx_requires_valid_range(__first, __last);
300 __glibcxx_requires_irreflexive(__first, __last);
301 __glibcxx_requires_heap(__first, __last);
302
303 if (__last - __first > 1)
304 {
305 --__last;
306 __gnu_cxx::__ops::_Iter_less_iter __comp;
307 std::__pop_heap(__first, __last, __last, __comp);
308 }
309 }
310
311 /**
312 * @brief Pop an element off a heap using comparison functor.
313 * @param __first Start of heap.
314 * @param __last End of heap.
315 * @param __comp Comparison functor to use.
316 * @ingroup heap_algorithms
317 *
318 * This operation pops the top of the heap. The elements __first
319 * and __last-1 are swapped and [__first,__last-1) is made into a
320 * heap. Comparisons are made using comp.
321 */
322 template<typename _RandomAccessIterator, typename _Compare>
323 _GLIBCXX20_CONSTEXPR
324 inline void
325 pop_heap(_RandomAccessIterator __first,
326 _RandomAccessIterator __last, _Compare __comp)
327 {
328 // concept requirements
329 __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept<
330 _RandomAccessIterator>)
331 __glibcxx_requires_valid_range(__first, __last);
332 __glibcxx_requires_irreflexive_pred(__first, __last, __comp);
333 __glibcxx_requires_non_empty_range(__first, __last);
334 __glibcxx_requires_heap_pred(__first, __last, __comp);
335
336 if (__last - __first > 1)
337 {
338 typedef __decltype(__comp) _Cmp;
339 __gnu_cxx::__ops::_Iter_comp_iter<_Cmp> __cmp(_GLIBCXX_MOVE(__comp));
340 --__last;
341 std::__pop_heap(__first, __last, __last, __cmp);
342 }
343 }
344
345 template<typename _RandomAccessIterator, typename _Compare>
346 _GLIBCXX20_CONSTEXPR
347 void
348 __make_heap(_RandomAccessIterator __first, _RandomAccessIterator __last,
349 _Compare& __comp)
350 {
351 typedef typename iterator_traits<_RandomAccessIterator>::value_type
352 _ValueType;
353 typedef typename iterator_traits<_RandomAccessIterator>::difference_type
354 _DistanceType;
355
356 if (__last - __first < 2)
357 return;
358
359 const _DistanceType __len = __last - __first;
360 _DistanceType __parent = (__len - 2) / 2;
361 while (true)
362 {
363 _ValueType __value = _GLIBCXX_MOVE(*(__first + __parent));
364 std::__adjust_heap(__first, __parent, __len, _GLIBCXX_MOVE(__value),
365 __comp);
366 if (__parent == 0)
367 return;
368 __parent--;
369 }
370 }
371
372 /**
373 * @brief Construct a heap over a range.
374 * @param __first Start of heap.
375 * @param __last End of heap.
376 * @ingroup heap_algorithms
377 *
378 * This operation makes the elements in [__first,__last) into a heap.
379 */
380 template<typename _RandomAccessIterator>
381 _GLIBCXX20_CONSTEXPR
382 inline void
383 make_heap(_RandomAccessIterator __first, _RandomAccessIterator __last)
384 {
385 // concept requirements
386 __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept<
387 _RandomAccessIterator>)
388 __glibcxx_function_requires(_LessThanComparableConcept<
390 __glibcxx_requires_valid_range(__first, __last);
391 __glibcxx_requires_irreflexive(__first, __last);
392
393 __gnu_cxx::__ops::_Iter_less_iter __comp;
394 std::__make_heap(__first, __last, __comp);
395 }
396
397 /**
398 * @brief Construct a heap over a range using comparison functor.
399 * @param __first Start of heap.
400 * @param __last End of heap.
401 * @param __comp Comparison functor to use.
402 * @ingroup heap_algorithms
403 *
404 * This operation makes the elements in [__first,__last) into a heap.
405 * Comparisons are made using __comp.
406 */
407 template<typename _RandomAccessIterator, typename _Compare>
408 _GLIBCXX20_CONSTEXPR
409 inline void
410 make_heap(_RandomAccessIterator __first, _RandomAccessIterator __last,
411 _Compare __comp)
412 {
413 // concept requirements
414 __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept<
415 _RandomAccessIterator>)
416 __glibcxx_requires_valid_range(__first, __last);
417 __glibcxx_requires_irreflexive_pred(__first, __last, __comp);
418
419 typedef __decltype(__comp) _Cmp;
420 __gnu_cxx::__ops::_Iter_comp_iter<_Cmp> __cmp(_GLIBCXX_MOVE(__comp));
421 std::__make_heap(__first, __last, __cmp);
422 }
423
424 template<typename _RandomAccessIterator, typename _Compare>
425 _GLIBCXX20_CONSTEXPR
426 void
427 __sort_heap(_RandomAccessIterator __first, _RandomAccessIterator __last,
428 _Compare& __comp)
429 {
430 while (__last - __first > 1)
431 {
432 --__last;
433 std::__pop_heap(__first, __last, __last, __comp);
434 }
435 }
436
437 /**
438 * @brief Sort a heap.
439 * @param __first Start of heap.
440 * @param __last End of heap.
441 * @ingroup heap_algorithms
442 *
443 * This operation sorts the valid heap in the range [__first,__last).
444 */
445 template<typename _RandomAccessIterator>
446 _GLIBCXX20_CONSTEXPR
447 inline void
448 sort_heap(_RandomAccessIterator __first, _RandomAccessIterator __last)
449 {
450 // concept requirements
451 __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept<
452 _RandomAccessIterator>)
453 __glibcxx_function_requires(_LessThanComparableConcept<
455 __glibcxx_requires_valid_range(__first, __last);
456 __glibcxx_requires_irreflexive(__first, __last);
457 __glibcxx_requires_heap(__first, __last);
458
459 __gnu_cxx::__ops::_Iter_less_iter __comp;
460 std::__sort_heap(__first, __last, __comp);
461 }
462
463 /**
464 * @brief Sort a heap using comparison functor.
465 * @param __first Start of heap.
466 * @param __last End of heap.
467 * @param __comp Comparison functor to use.
468 * @ingroup heap_algorithms
469 *
470 * This operation sorts the valid heap in the range [__first,__last).
471 * Comparisons are made using __comp.
472 */
473 template<typename _RandomAccessIterator, typename _Compare>
474 _GLIBCXX20_CONSTEXPR
475 inline void
476 sort_heap(_RandomAccessIterator __first, _RandomAccessIterator __last,
477 _Compare __comp)
478 {
479 // concept requirements
480 __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept<
481 _RandomAccessIterator>)
482 __glibcxx_requires_valid_range(__first, __last);
483 __glibcxx_requires_irreflexive_pred(__first, __last, __comp);
484 __glibcxx_requires_heap_pred(__first, __last, __comp);
485
486 typedef __decltype(__comp) _Cmp;
487 __gnu_cxx::__ops::_Iter_comp_iter<_Cmp> __cmp(_GLIBCXX_MOVE(__comp));
488 std::__sort_heap(__first, __last, __cmp);
489 }
490
491#if __cplusplus >= 201103L
492 /**
493 * @brief Search the end of a heap.
494 * @param __first Start of range.
495 * @param __last End of range.
496 * @return An iterator pointing to the first element not in the heap.
497 * @ingroup heap_algorithms
498 *
499 * This operation returns the last iterator i in [__first, __last) for which
500 * the range [__first, i) is a heap.
501 */
502 template<typename _RandomAccessIterator>
503 _GLIBCXX_NODISCARD _GLIBCXX20_CONSTEXPR
504 inline _RandomAccessIterator
505 is_heap_until(_RandomAccessIterator __first, _RandomAccessIterator __last)
506 {
507 // concept requirements
508 __glibcxx_function_requires(_RandomAccessIteratorConcept<
509 _RandomAccessIterator>)
510 __glibcxx_function_requires(_LessThanComparableConcept<
512 __glibcxx_requires_valid_range(__first, __last);
513 __glibcxx_requires_irreflexive(__first, __last);
514
515 __gnu_cxx::__ops::_Iter_less_iter __comp;
516 return __first +
517 std::__is_heap_until(__first, std::distance(__first, __last), __comp);
518 }
519
520 /**
521 * @brief Search the end of a heap using comparison functor.
522 * @param __first Start of range.
523 * @param __last End of range.
524 * @param __comp Comparison functor to use.
525 * @return An iterator pointing to the first element not in the heap.
526 * @ingroup heap_algorithms
527 *
528 * This operation returns the last iterator i in [__first, __last) for which
529 * the range [__first, i) is a heap. Comparisons are made using __comp.
530 */
531 template<typename _RandomAccessIterator, typename _Compare>
532 _GLIBCXX_NODISCARD _GLIBCXX20_CONSTEXPR
533 inline _RandomAccessIterator
534 is_heap_until(_RandomAccessIterator __first, _RandomAccessIterator __last,
535 _Compare __comp)
536 {
537 // concept requirements
538 __glibcxx_function_requires(_RandomAccessIteratorConcept<
539 _RandomAccessIterator>)
540 __glibcxx_requires_valid_range(__first, __last);
541 __glibcxx_requires_irreflexive_pred(__first, __last, __comp);
542
543 typedef __decltype(__comp) _Cmp;
544 __gnu_cxx::__ops::_Iter_comp_iter<_Cmp> __cmp(_GLIBCXX_MOVE(__comp));
545 return __first
546 + std::__is_heap_until(__first, std::distance(__first, __last), __cmp);
547 }
548
549 /**
550 * @brief Determines whether a range is a heap.
551 * @param __first Start of range.
552 * @param __last End of range.
553 * @return True if range is a heap, false otherwise.
554 * @ingroup heap_algorithms
555 */
556 template<typename _RandomAccessIterator>
557 _GLIBCXX_NODISCARD _GLIBCXX20_CONSTEXPR
558 inline bool
559 is_heap(_RandomAccessIterator __first, _RandomAccessIterator __last)
560 { return std::is_heap_until(__first, __last) == __last; }
561
562 /**
563 * @brief Determines whether a range is a heap using comparison functor.
564 * @param __first Start of range.
565 * @param __last End of range.
566 * @param __comp Comparison functor to use.
567 * @return True if range is a heap, false otherwise.
568 * @ingroup heap_algorithms
569 */
570 template<typename _RandomAccessIterator, typename _Compare>
571 _GLIBCXX_NODISCARD _GLIBCXX20_CONSTEXPR
572 inline bool
573 is_heap(_RandomAccessIterator __first, _RandomAccessIterator __last,
574 _Compare __comp)
575 {
576 // concept requirements
577 __glibcxx_function_requires(_RandomAccessIteratorConcept<
578 _RandomAccessIterator>)
579 __glibcxx_requires_valid_range(__first, __last);
580 __glibcxx_requires_irreflexive_pred(__first, __last, __comp);
581
582 const auto __dist = std::distance(__first, __last);
583 typedef __decltype(__comp) _Cmp;
584 __gnu_cxx::__ops::_Iter_comp_iter<_Cmp> __cmp(_GLIBCXX_MOVE(__comp));
585 return std::__is_heap_until(__first, __dist, __cmp) == __dist;
586 }
587#endif
588
589_GLIBCXX_END_NAMESPACE_VERSION
590} // namespace
591
592#endif /* _STL_HEAP_H */
ISO C++ entities toplevel namespace is std.
constexpr iterator_traits< _InputIterator >::difference_type distance(_InputIterator __first, _InputIterator __last)
A generalization of pointer arithmetic.
Traits class for iterators.