Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_dynArrayHeap.H
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
31
53# ifndef TPL_DYNARRAYHEAP_H
54# define TPL_DYNARRAYHEAP_H
55
56# include <ah-concepts.H>
57# include <algorithm>
58# include <climits>
59# include <cstddef>
60# include <memory>
61# include <stdexcept>
62# include <type_traits>
63# include <utility>
64
65# include <tpl_dynArray.H>
66# include <ah-errors.H>
67#include <ah-iterator.H>
68
69namespace Aleph
70{
71 namespace dynarrayheap_detail
72 {
74 template <typename T>
75 struct Way
76 {
77 T *at[sizeof(size_t) * CHAR_BIT];
78 size_t len = 0;
79 };
80
97 template <typename T, class Compare>
98 inline
99 size_t up_index(DynArray<T> & a, const size_t l, const size_t r, T & x,
100 Compare & cmp, Way<T> & way)
102 {
103 size_t i = r;
104 while (i > l)
105 {
106 const size_t p = u_index(i); // parent index (p = i / 2)
107
108 // Prefetch grandparent for next iteration
109 if (const size_t gp = u_index(p); gp >= l)
110 __builtin_prefetch(std::addressof(a.access(gp)), 0, 1);
111
112 T & ap = a.access(p);
113 if (cmp(ap, x)) [[likely]] // heap property holds
114 break;
115 way.at[way.len++] = std::addressof(ap);
116 i = p;
117 }
118 return i;
119 }
120
135 template <typename T, class Compare>
136 inline
137 size_t down_index(DynArray<T> & a, const size_t l, const size_t r, T & x,
138 Compare & cmp, Way<T> & way)
140 {
141 size_t i = l;
142 while (true)
143 {
144 size_t c = l_index(i); // left child index (c = 2 * i)
145 if (c > r) [[unlikely]] // no left child
146 return i;
147
148 // Prefetch grandchildren for next iteration
149 if (const size_t gc = l_index(c); gc <= r)
150 __builtin_prefetch(std::addressof(a.access(gc)), 0, 1);
151
152 T *ac = std::addressof(a.access(c));
153 if (c + 1 <= r) // right child exists
154 {
155 T *ac1 = std::addressof(a.access(c + 1));
156 if (cmp(*ac1, *ac)) // pick the child with higher priority
157 {
158 c++;
159 ac = ac1;
160 }
161 }
162
163 if (cmp(x, *ac)) [[likely]] // heap property holds
164 return i;
165 way.at[way.len++] = ac;
166 i = c;
167 }
168 }
169
182 template <typename T>
183 inline
184 void shift(T & first, const Way<T> & way, T & x)
185 {
186 T *hole = std::addressof(first);
187 for (size_t k = 0; k < way.len; ++k)
188 {
189 *hole = std::move(*way.at[k]);
190 hole = way.at[k];
191 }
192 *hole = std::move(x);
193 }
194 }
195
209 template <typename T, class Compare>
210 inline
211 size_t sift_up(DynArray<T> & a, const size_t l, const size_t r, Compare & cmp)
213 {
214 T & x = a.access(r);
216 const size_t i = dynarrayheap_detail::up_index(a, l, r, x, cmp, way);
217 if (i != r)
218 {
219 T moving = std::move(x);
220 dynarrayheap_detail::shift(x, way, moving);
221 }
222 return i;
223 }
224
237 template <typename T, class Compare>
238 inline
239 void sift_down(DynArray<T> & a, const size_t l, const size_t r, Compare & cmp)
241 {
242 T & x = a.access(l);
244 if (dynarrayheap_detail::down_index(a, l, r, x, cmp, way) != l)
245 {
246 T moving = std::move(x);
247 dynarrayheap_detail::shift(x, way, moving);
248 }
249 }
250
251
260 template <typename T, class Compare = Aleph::less<T>>
261 requires StrictWeakOrder<Compare, T>
262 class DynArrayHeap : public LocateFunctions<DynArrayHeap<T, Compare>, T>,
263 public FunctionalMethods<DynArrayHeap<T, Compare>, T>,
264 public GenericKeys<DynArrayHeap<T, Compare>, T>,
265 public StlAlephIterator<DynArrayHeap<T, Compare>>
266 {
268 size_t num_items = 0;
269
270 Compare cmp;
271
272 static size_t r_index(const size_t & i) noexcept
273 {
274 return (i << 1) + 1; // right child index
275 }
276
295 [[gnu::always_inline]] inline
296 T & enter(T & key, T & item, T & place, const size_t r)
297 {
299 size_t i;
300 try
301 {
302 i = dynarrayheap_detail::up_index(array, 1, r, item, cmp, way);
303 }
304 catch (...)
305 {
306 key = std::move(item);
307 throw;
308 }
309 dynarrayheap_detail::shift(place, way, item);
310 ++num_items;
311 return array.access(i);
312 }
313
314 public:
315 using Item_Type = T;
316
318 DynArrayHeap(Compare cmp_fct = Compare()) : cmp(cmp_fct)
319 {
320 // empty
321 }
322
324
326
330 DynArrayHeap(const DynArrayHeap & other) = default;
331
340 DynArrayHeap(DynArrayHeap && other) noexcept(
341 std::is_nothrow_move_constructible_v<DynArray<T>> and
342 std::is_nothrow_copy_constructible_v<Compare>)
343 : array(std::move(other.array)), num_items(std::exchange(other.num_items, 0)),
344 cmp(other.cmp)
345 {}
346
351 DynArrayHeap & operator = (const DynArrayHeap & other) = default;
352
358 DynArrayHeap & operator = (DynArrayHeap && other) noexcept(noexcept(swap(other)))
359 {
360 swap(other);
361 return *this;
362 }
363
374 void swap(DynArrayHeap & other) noexcept(
375 std::is_nothrow_swappable_v<T> and std::is_nothrow_swappable_v<Compare>)
376 {
377 // the swap that the specification evaluates: that of Compare found by
378 // its arguments, else std::swap(); first, since it may throw
379 using std::swap;
380 swap(cmp, other.cmp);
381 if constexpr (std::is_nothrow_swappable_v<T>)
382 array.swap(other.array);
383 else
384 try
385 {
386 array.swap(other.array);
387 }
388 catch (...)
389 {
390 swap(cmp, other.cmp);
391 throw;
392 }
393 std::swap(num_items, other.num_items);
394 }
395
404 {
405 ah_underflow_error_if(num_items == 0) << "Heap is empty";
406
407 return array.access(1);
408 }
409
411 const T &top() const
412 {
413 ah_underflow_error_if(num_items == 0) << "Heap is empty";
414
415 return array.access(1);
416 }
417
428 T &insert(const T & key)
429 {
430 // The copy, the comparisons and the place come before any move, so
431 // that if one throws, the heap is as it was. The comparisons take the
432 // copy, which is not constant, as they take the items of the array
433 T item = key;
434 const size_t r = num_items + 1;
436 const size_t i = dynarrayheap_detail::up_index(array, 1, r, item, cmp, way);
437 dynarrayheap_detail::shift(array.touch(r), way, item);
438 ++num_items;
439 return array.access(i);
440 }
441
458 T &insert(T && key)
459 {
460 const size_t r = num_items + 1;
461 T & place = array.touch(r); // first: without memory, the key is not moved
462 T item = std::move(key);
463 return enter(key, item, place, r);
464 }
465
470 void reserve(size_t n)
471 {
472 ah_out_of_range_error_if(num_items > n) << "DynArrayHeap::reserve: n smaller than size";
473 array.reserve(n);
474 }
475
483 T &insert_direct(const T & key)
484 {
485 T item = key; // not constant, for the comparisons: see insert()
486 const size_t r = num_items + 1;
488 const size_t i = dynarrayheap_detail::up_index(array, 1, r, item, cmp, way);
489 dynarrayheap_detail::shift(array.access(r), way, item);
490 ++num_items;
491 return array.access(i);
492 }
493
502 {
503 const size_t r = num_items + 1;
504 T item = std::move(key);
505 return enter(key, item, array.access(r), r);
506 }
507
509 T &put(const T & key) { return insert(key); }
510
512 T &put(T && key) { return insert(std::move(key)); }
513
515 T &append(const T & key) { return insert(key); }
516
518 T &append(T && key) { return insert(std::move(key)); }
519
529 {
530 ah_underflow_error_if(num_items == 0) << "Heap is empty";
531
532 // The comparisons come before any move, with the last item as if it
533 // were at the root, so that if one throws, the heap is as it was
534 const size_t last = num_items;
536 if (last > 1)
537 dynarrayheap_detail::down_index(array, 1, last - 1, array.access(last), cmp, way);
538 T & root = array(1);
539 T ret_val = std::move(root);
540 if (last > 1) // the last item is not on its way, which ends before it
541 dynarrayheap_detail::shift(root, way, array.access(last));
542 --num_items;
543
544 array.cut(num_items + 1);
545
546 return ret_val;
547 }
548
551 {
552 return getMin();
553 }
554
557 {
558 return getMin();
559 }
560
562 [[nodiscard]] constexpr size_t size() const noexcept { return num_items; }
563
565 [[nodiscard]] constexpr bool is_empty() const noexcept { return num_items == 0; }
566
577 {
578 const DynArrayHeap *heap_ptr = nullptr;
579 long curr_idx = 0;
580
582 [[nodiscard]] long items() const noexcept
583 {
584 return heap_ptr == nullptr ? 0 : static_cast<long>(heap_ptr->num_items);
585 }
586
587 public:
589 using Item_Type = T;
590
592 Iterator() noexcept = default;
593
598 Iterator(const DynArrayHeap & h) noexcept : heap_ptr(&h) {}
599
601 [[nodiscard]] bool has_curr() const noexcept { return curr_idx >= 0 and curr_idx < items(); }
602
604 [[nodiscard]] bool is_last() const noexcept { return has_curr() and curr_idx == items() - 1; }
605
607 [[nodiscard]] const T & get_curr_ne() const noexcept
608 {
609 return heap_ptr->array.access(static_cast<size_t>(curr_idx) + 1);
610 }
611
619 [[nodiscard]] const T & get_curr() const
620 {
621 ah_underflow_error_if(curr_idx < 0) << "not current item in iterator";
622 ah_overflow_error_if(curr_idx >= items()) << "not current item in iterator";
623 return get_curr_ne();
624 }
625
627 [[nodiscard]] long get_pos() const noexcept { return curr_idx; }
628
630 void set_pos(const long pos) noexcept { curr_idx = pos; }
631
633 void next_ne() noexcept { ++curr_idx; }
634
640 void next()
641 {
642 ah_overflow_error_if(heap_ptr == nullptr or curr_idx >= items())
643 << "not current item in iterator";
644 next_ne();
645 }
646
648 void prev_ne() noexcept { --curr_idx; }
649
655 void prev()
656 {
657 ah_underflow_error_if(curr_idx < 0) << "not current item in iterator";
658 prev_ne();
659 }
660
662 void reset_first() noexcept { curr_idx = 0; }
663
665 void reset_last() noexcept { curr_idx = items() - 1; }
666
668 void end() noexcept { curr_idx = items(); }
669 };
670
673
680 template <class Operation>
682 bool traverse(Operation & operation)
684 {
685 for (size_t i = 1; i <= num_items; ++i) // the items are entries 1 to num_items
686 if (not static_cast<bool>(operation(array.access(i))))
687 return false;
688 return true;
689 }
690
691 template <class Operation>
693 bool traverse(Operation & operation) const
695 {
696 for (size_t i = 1; i <= num_items; ++i)
697 if (not static_cast<bool>(operation(static_cast<const T &>(array.access(i)))))
698 return false;
699 return true;
700 }
701
702 template <class Operation>
704 bool traverse(Operation && operation = Operation()) const
705 {
706 return traverse<Operation>(operation);
707 }
708
709 template <class Operation>
711 bool traverse(Operation && operation = Operation())
712 {
713 return traverse<Operation>(operation);
714 }
715 };
716} // end namespace Aleph
717
718# endif // TPL_DYNARRAYHEAP_H
#define Args_Ctor(Name, Type)
C++20 concepts hub: comparison, BST policy, and Aleph container concepts.
Exception handling system with formatted messages for Aleph-w.
#define ah_out_of_range_error_if(C)
Throws std::out_of_range if condition holds.
Definition ah-errors.H:727
#define ah_underflow_error_if(C)
Throws std::underflow_error if condition holds.
Definition ah-errors.H:517
#define ah_overflow_error_if(C)
Throws std::overflow_error if condition holds.
Definition ah-errors.H:611
STL-compatible iterator adapters for Aleph containers.
#define Special_Ctors(Set_Type, Type)
Generates special constructors for containers.
Definition ahDry.H:123
long double h
Definition btreepic.C:154
Read-only view of an Aleph iterator: the iterator of a constant container.
Iterator on the items of the heap, in the order of its array, which is not the sorted one.
const T & get_curr_ne() const noexcept
The current item, without checking that there is one.
Iterator() noexcept=default
An iterator without a heap, which has no items.
long items() const noexcept
The number of items of the heap; none without a heap.
T Item_Type
The type of the items.
void prev_ne() noexcept
Move one position backward, without checking.
const T & get_curr() const
The current item, read-only: the heap order must not be broken.
void reset_first() noexcept
Put the iterator on the first item.
bool is_last() const noexcept
Return true if the iterator is on the last item.
void set_pos(const long pos) noexcept
Put the iterator on the position pos, without checking it.
bool has_curr() const noexcept
Return true if the iterator is on an item.
void reset_last() noexcept
Put the iterator on the last item.
void next_ne() noexcept
Move one position forward, without checking.
const DynArrayHeap * heap_ptr
The heap; none in an iterator built without one.
void prev()
Move one position backward, from the first item to before it too.
long get_pos() const noexcept
The position of the current item among those of the heap, from 0.
void next()
Move one position forward, from the last item to the end too.
long curr_idx
The position of the current item, from 0.
void end() noexcept
Put the iterator at the end, after the last item.
Dynamic heap (priority queue) backed by DynArray.
T & insert_direct(T &&key)
Move overload of insert_direct().
static size_t r_index(const size_t &i) noexcept
DynArrayHeap(const DynArrayHeap &other)=default
Copy the elements and the comparator of another heap.
DynArrayHeap(Compare cmp_fct=Compare())
Default constructor.
T & put(T &&key)
Alias for insert() (move overload).
void swap(DynArrayHeap &other) noexcept(std::is_nothrow_swappable_v< T > and std::is_nothrow_swappable_v< Compare >)
Exchange in O(1) the elements and the comparators of this heap and another.
void reserve(size_t n)
Ensure the underlying array has capacity for at least n elements.
constexpr bool is_empty() const noexcept
Return true if the heap is empty.
T getMin()
Remove and return the top element.
T & put(const T &key)
Alias for insert().
T get()
See getMin().
T & append(const T &key)
Alias for insert().
T & enter(T &key, T &item, T &place, const size_t r)
Take to its place the item moved from the key of an insertion.
bool traverse(Operation &&operation=Operation())
T & insert(const T &key)
Insert a copy of key into the heap.
T getMax()
See getMin(); useful if priority order is inverted.
T & insert(T &&key)
Insert a key by moving it into the heap.
T & top()
Return the element with highest priority (the heap top).
bool traverse(Operation &operation) const noexcept(Aleph::NothrowPredicateWith< Operation &, const T & >)
T & insert_direct(const T &key)
Insert by directly indexing into the backing array.
const T & top() const
Const overload of top().
DynArrayHeap & operator=(const DynArrayHeap &other)=default
Copy the elements and the comparator of another heap.
bool traverse(Operation &operation) noexcept(Aleph::NothrowPredicateWith< Operation &, T & >)
Traverse all elements in the heap.
bool traverse(Operation &&operation=Operation()) const
T & append(T &&key)
Alias for insert() (move overload).
DynArrayHeap(DynArrayHeap &&other) noexcept(std::is_nothrow_move_constructible_v< DynArray< T > > and std::is_nothrow_copy_constructible_v< Compare >)
Take the elements of another heap, which is left empty.
constexpr size_t size() const noexcept
Return the number of elements.
Common methods to the Aleph-w ( ) containers.
Definition ah-dry.H:1235
and
Insert a new element into the container by constructing it from the given args.
Definition ah-dry.H:1273
Common sequential searching methods on containers.
Definition ah-dry.H:555
Mixin that adds STL begin()/end() and cbegin()/cend() to Aleph containers.
PredicateWith<F, Args...>, and neither the call nor the conversion of its result to bool can throw.
f(args...) is a valid call whose result is usable as a condition.
__gmp_expr< T, __gmp_binary_expr< __gmp_expr< T, U >, unsigned long int, __gmp_root_function > > root(const __gmp_expr< T, U > &expr, unsigned long int l)
Definition gmpfrxx.h:4138
int cmp(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4196
size_t up_index(DynArray< T > &a, const size_t l, const size_t r, T &x, Compare &cmp, Way< T > &way) noexcept(Aleph::NothrowPredicateWith< Compare &, T &, T & >)
Find where an item that enters at the end of a heap goes.
size_t down_index(DynArray< T > &a, const size_t l, const size_t r, T &x, Compare &cmp, Way< T > &way) noexcept(Aleph::NothrowPredicateWith< Compare &, T &, T & >)
Find where an item that enters at the root of a heap goes.
void shift(T &first, const Way< T > &way, T &x)
Move an item along its way.
Main namespace for Aleph-w library functions.
void sift_down(T *ptr, const size_t l, const size_t r, Compare &cmp)
Restore the heap property by moving the element at position l downwards.
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
constexpr size_t l_index(const size_t i)
Map a binary heap index to the index of its left child.
Definition ahUtils.H:218
constexpr size_t u_index(const size_t &i)
Map a binary heap index to the index of its parent.
Definition ahUtils.H:204
T & sift_up(T *ptr, const size_t l, const size_t r, Compare &cmp)
Restore the heap property by moving the element at position r upwards.
STL namespace.
The places that an item passes, in order, when it is sifted.
size_t len
The number of places.
T * at[sizeof(size_t) *CHAR_BIT]
The places, from the first one.
Generic list of items stored in a container.
Definition ah-dry.H:2896
static int * k
Gsl_Compatible_Rng r
Lazy and scalable dynamic array implementation.
DynList< int > l