Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
arrayheap.cc
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
32
38#include <algorithm>
39#include <cstdint>
40#include <memory>
41#include <new>
42#include <numeric>
43#include <ostream>
44#include <random>
45#include <ranges>
46#include <stdexcept>
47#include <type_traits>
48#include <utility>
49#include <vector>
50
51#include <gtest/gtest.h>
52
53#include <tpl_array.H>
54#include <tpl_arrayHeap.H>
55
56using namespace Aleph;
57using namespace testing;
58
59TEST(ArrayHeap, InsertAndExtract)
60{
61 ArrayHeap<int> heap(8);
62 heap.insert(3);
63 heap.insert(1);
64 heap.insert(2);
65
66 EXPECT_EQ(heap.size(), 3u);
67 EXPECT_FALSE(heap.is_empty());
68 EXPECT_EQ(heap.top(), 1);
69
70 EXPECT_EQ(heap.getMin(), 1);
71 EXPECT_EQ(heap.top(), 2);
72 EXPECT_EQ(heap.get(), 2);
73 EXPECT_EQ(heap.getMax(), 3); // alias of getMin when comparator flips
74 EXPECT_TRUE(heap.is_empty());
75}
76
77TEST(ArrayHeap, UpdateAndRemove)
78{
79 ArrayHeap<int> heap(5);
80 auto & ref = heap.insert(5);
81 const auto & ref2 = heap.insert(7);
82
83 ref = 1;
84 heap.update(ref);
85 EXPECT_EQ(heap.top(), 1);
86 EXPECT_EQ(ref2, 7);
87
88 heap.remove(ref);
89 EXPECT_EQ(heap.size(), 1u);
90 EXPECT_EQ(heap.top(), 7);
91}
92
93TEST(ArrayHeap, CapacityOverflow)
94{
95 ArrayHeap<int> heap(2);
96 heap.insert(10);
97 heap.insert(20);
98 EXPECT_THROW(heap.insert(30), std::overflow_error);
99}
100
101TEST(ArrayHeap, ExtractsSortedOrder)
102{
103 ArrayHeap<int> heap(10);
104 const std::vector<int> input{5, 3, 8, 1, 4, 9, 2, 7};
105 for (int value : input)
106 heap.insert(value);
107
108 std::vector<int> drained;
109 while (!heap.is_empty())
110 drained.push_back(heap.getMin());
111
112 std::vector<int> sorted = input;
113 std::sort(sorted.begin(), sorted.end());
114 EXPECT_EQ(drained, sorted);
115 EXPECT_TRUE(heap.is_empty());
116}
117
118// ─────────────────────────────────────────────────────────────────
119// A comparison that throws
120// ─────────────────────────────────────────────────────────────────
121
122namespace
123{
124 // An item with a priority, which the comparisons look at, and an
125 // identity, which they do not: it tells apart the items of a priority.
126 // A move takes the identity of its source away
127 struct Item
128 {
129 static constexpr int gone = -1;
130
131 int pri = 0;
132 int id = 0;
133
134 Item() = default;
135 Item(const int p, const int i) noexcept : pri(p), id(i) {}
136 Item(const Item &) = default;
137 Item & operator=(const Item &) = default;
138 Item(Item && o) noexcept : pri(o.pri), id(std::exchange(o.id, gone)) {}
139 Item & operator=(Item && o) noexcept
140 {
141 pri = o.pri;
142 id = std::exchange(o.id, gone);
143 return *this;
144 }
145 bool operator==(const Item &) const = default;
146 };
147
148 void PrintTo(const Item & x, std::ostream *os) { *os << x.pri << '#' << x.id; }
149
150 // The key of an insertion by move takes its item back by a move
151 // assignment when the comparison throws: the heap promises to be as it
152 // was only if that assignment does not throw, as with these items
153 static_assert(std::is_nothrow_move_assignable_v<Item>);
154
155 // The calls of a Counted_Less: how many, the one that throws (0: none),
156 // and the identities of the two items of each one, in order
157 struct Calls
158 {
159 size_t count = 0;
160 size_t throw_at = 0;
161 std::vector<std::pair<int, int>> items;
162 };
163
164 template <class X>
165 struct Counted_Less_Of
166 {
167 Calls *calls;
168
169 bool operator()(const X & a, const X & b) const
170 {
171 if (++calls->count == calls->throw_at)
172 throw std::runtime_error("comparison");
173 calls->items.emplace_back(a.id, b.id);
174 return a.pri < b.pri;
175 }
176 };
177
178 using Counted_Less = Counted_Less_Of<Item>;
179 using Counted_Heap = ArrayHeap<Item, Counted_Less>;
180
181 // The items of a heap, in the order of its array
182 template <class X>
183 std::vector<X> layout(const ArrayHeap<X, Counted_Less_Of<X>> & h)
184 {
185 std::vector<X> items;
186 for (size_t i = 1; i <= h.size(); ++i)
187 items.push_back(h[i]);
188 return items;
189 }
190
191 // The heap of 7.7.5, on a vector whose entry 0 is not used: its sifts
192 // exchanged an item with its parent or its child at each level, and its
193 // operations stored and counted before they compared
194 template <class X>
195 struct Old_Heap_Of
196 {
197 std::vector<X> a = std::vector<X>(1);
198 size_t n = 0;
199 Counted_Less_Of<X> cmp;
200
201 void sift_up(const size_t l, const size_t r)
202 {
203 for (size_t p, i = r; i > l; i = p)
204 {
205 p = i / 2;
206 if (cmp(a[p], a[i]))
207 return;
208 std::swap(a[p], a[i]);
209 }
210 }
211
212 void sift_down(const size_t l, const size_t r)
213 {
214 for (size_t i = l; ;)
215 {
216 size_t c = 2 * i;
217 if (c > r)
218 return;
219 if (c + 1 <= r and cmp(a[c + 1], a[c]))
220 ++c;
221 if (cmp(a[i], a[c]))
222 return;
223 std::swap(a[c], a[i]);
224 i = c;
225 }
226 }
227
228 void sift_down_up(const size_t l, const size_t i, const size_t r)
229 {
230 sift_down(i, r);
231 sift_up(l, i);
232 }
233
234 void insert(X && x)
235 {
236 a.resize(std::max(a.size(), n + 2));
237 a[n + 1] = std::move(x); // x may be one of the items
238 sift_up(1, ++n);
239 }
240
241 void insert(const X & x) { insert(X(x)); }
242
243 X getMin()
244 {
245 const X ret = a[1];
246 a[1] = a[n--];
247 if (n > 0)
248 sift_down(1, n);
249 return ret;
250 }
251
252 void update(const size_t i) { sift_down_up(1, i, n); }
253
254 void remove(const size_t i)
255 {
256 if (i == n)
257 {
258 --n;
259 return;
260 }
261 a[i] = a[n--];
262 sift_down_up(1, i, n);
263 }
264
265 std::vector<X> layout() const { return {a.begin() + 1, a.begin() + 1 + static_cast<long>(n)}; }
266 };
267
268 using Old_Heap = Old_Heap_Of<Item>;
269
270 // An item whose move leaves in its source the priority `left`, which
271 // each test chooses, and no identity
272 struct Husk
273 {
274 static inline int left = 0;
275
276 int pri = 0;
277 int id = 0;
278
279 Husk() = default;
280 Husk(const int p, const int i) noexcept : pri(p), id(i) {}
281 Husk(const Husk &) = default;
282 Husk & operator=(const Husk &) = default;
283 Husk(Husk && o) noexcept : pri(std::exchange(o.pri, left)), id(std::exchange(o.id, 0)) {}
284 Husk & operator=(Husk && o) noexcept
285 {
286 pri = std::exchange(o.pri, left);
287 id = std::exchange(o.id, 0);
288 return *this;
289 }
290 bool operator==(const Husk &) const = default;
291 };
292
293 static_assert(std::is_nothrow_move_assignable_v<Husk>);
294
295 void PrintTo(const Husk & x, std::ostream *os) { *os << x.pri << '#' << x.id; }
296
297 using Husk_Less = Counted_Less_Of<Husk>;
298 using Husk_Heap = ArrayHeap<Husk, Husk_Less>;
299}
300
301// The new sifts compare the same items in the same order as those of
302// 7.7.5, and leave every item in the same place, those of a same priority
303// too: in the insertions, of a copy and of a move, in the extractions, in
304// the removals of any item and in the updates of an item whose priority
305// changed
306TEST(ArrayHeapThrowingCompare, SameComparisonsAndPlacesAsTheOldSifts)
307{
308 std::mt19937 rng(77);
309 std::uniform_int_distribution<int> values(0, 50); // many items of a same priority
310 Calls calls, old_calls;
311 Counted_Heap heap(6000, Counted_Less{&calls});
312 Old_Heap old{.cmp = Counted_Less{&old_calls}};
313 size_t updates = 0;
314 size_t removals = 0;
315 for (int k = 0; k < 6000; ++k)
316 {
317 const unsigned op = old.n == 0 ? 0 : rng() % 8;
318 if (op < 4)
319 {
320 const Item x(values(rng), k + 1);
321 switch (op)
322 {
323 case 0: heap.insert(x); break;
324 case 1: heap.insert(Item(x)); break;
325 case 2: heap.insert_ne(x); break;
326 default: heap.insert_ne(Item(x));
327 }
328 old.insert(x);
329 }
330 else if (op == 4)
331 {
332 const Item min = heap.getMin();
333 ASSERT_EQ(min, old.getMin());
334 }
335 else if (op == 5)
336 {
337 const size_t i = 1 + rng() % old.n;
338 heap.remove(heap[i]);
339 old.remove(i);
340 ++removals;
341 }
342 else
343 {
344 const size_t i = 1 + rng() % old.n;
345 const int pri = values(rng);
346 heap[i].pri = pri;
347 old.a[i].pri = pri;
348 heap.update(heap[i]);
349 old.update(i);
350 ++updates;
351 }
352 ASSERT_EQ(calls.items, old_calls.items) << "operation " << k;
353 calls.items.clear();
354 old_calls.items.clear();
355 ASSERT_EQ(layout(heap), old.layout()) << "operation " << k;
356 }
357 EXPECT_GT(updates, 1000u);
358 EXPECT_GT(removals, 500u);
359 EXPECT_GT(heap.size(), 100u);
360}
361
362// Each failed comparison of an insertion, an extraction, a removal or an
363// update leaves the heap as it was: its items in the same places, none
364// moved from, and its size, with the key of an insertion by move untouched.
365// 7.7.5 left the item counted, or the minimum lost, and the heap out of
366// order
367TEST(ArrayHeapThrowingCompare, EveryFailedCallLeavesTheHeapAsItWas)
368{
369 std::mt19937 rng(20261121);
370 std::uniform_int_distribution<int> values(0, 30);
371 size_t failed = 0;
372 for (size_t n = 0; n <= 40; ++n)
373 for (int op = 0; op < 7; ++op) // 0-3 insertions; 4 getMin; 5 remove; 6 update
374 {
375 if (op >= 4 and n == 0)
376 continue;
377 std::vector<Item> items;
378 for (size_t k = 0; k < n; ++k)
379 items.emplace_back(values(rng), static_cast<int>(k + 1));
380 const Item key(values(rng), static_cast<int>(n + 1));
381 const size_t where = n == 0 ? 0 : 1 + rng() % n; // of the removal and of the update
382 const int new_pri = values(rng);
383 for (size_t at = 1; ; ++at)
384 {
385 SCOPED_TRACE(testing::Message() << "n " << n << ", op " << op << ", call " << at);
386 Calls calls;
387 Counted_Heap heap(n + 2, Counted_Less{&calls});
388 for (const Item & x : items)
389 heap.insert(x);
390 if (op == 6)
391 heap[where].pri = new_pri; // the heap is as its user left it
392 const std::vector<Item> before = layout(heap);
393 calls.throw_at = calls.count + at;
394 bool thrown = false;
395 Item moved = key;
396 try
397 {
398 switch (op)
399 {
400 case 0: heap.insert(key); break;
401 case 1: heap.insert(std::move(moved)); break;
402 case 2: heap.insert_ne(key); break;
403 case 3: heap.insert_ne(std::move(moved)); break;
404 case 4: (void) heap.getMin(); break;
405 case 5: heap.remove(heap[where]); break;
406 default: heap.update(heap[where]);
407 }
408 }
409 catch (const std::runtime_error &)
410 {
411 thrown = true;
412 }
413 calls.throw_at = 0;
414 if (not thrown)
415 {
416 ASSERT_TRUE(valid_heap(&heap[0], 1, heap.size(), Counted_Less{&calls}));
417 break;
418 }
419 ++failed;
420 EXPECT_EQ(heap.size(), n);
421 EXPECT_EQ(layout(heap), before);
422 EXPECT_EQ(moved, key);
423 }
424 }
425 EXPECT_GT(failed, 500u);
426}
427
428// A comparison that throws once, as in the notes of 7.7.5 for
429// DynArrayHeap: insert(1) on a heap that holds 5 left the size at 2 and the
430// top at 5, and getMin() on 1, 2, 3 and 4 left the size at 3, lost the 1,
431// and then gave 4, 2 and 3
432TEST(ArrayHeapThrowingCompare, OneThrowLosesNothing)
433{
434 struct Once
435 {
436 bool *armed;
437
438 bool operator()(const int a, const int b) const
439 {
440 if (std::exchange(*armed, false))
441 throw std::runtime_error("comparison");
442 return a < b;
443 }
444 };
445
446 bool armed = false;
447 {
448 ArrayHeap<int, Once> heap(8, Once{&armed});
449 heap.insert(5);
450 armed = true;
451 EXPECT_THROW(heap.insert(1), std::runtime_error);
452 EXPECT_EQ(heap.size(), 1u);
453 EXPECT_EQ(heap.top(), 5);
454 }
455 {
456 ArrayHeap<int, Once> heap(8, Once{&armed});
457 for (const int i : {1, 2, 3, 4})
458 heap.insert(i);
459 armed = true;
460 EXPECT_THROW((void) heap.getMin(), std::runtime_error);
461 EXPECT_EQ(heap.size(), 4u);
462 std::vector<int> drained;
463 while (not heap.is_empty())
464 drained.push_back(heap.getMin());
465 EXPECT_EQ(drained, (std::vector<int>{1, 2, 3, 4}));
466 }
467}
468
469// The key of an insertion by move may be an item of the heap itself, which
470// the move changes where it is. The key is moved before the comparisons, as
471// in 7.7.5, so that they see that item as it is left: the same comparisons
472// and the same places as then, whatever the place of the item, on the way
473// of the new one or not, and whatever the move leaves in it, before the
474// other items, among them or after them
475TEST(ArrayHeapThrowingCompare, AKeyThatItsMoveChangesInTheHeap)
476{
477 for (const int left : {-1, 1, 99}) // the priorities are 0, 1 and 2
478 for (const bool checked : {false, true})
479 for (int n = 1; n <= 12; ++n)
480 for (int place = 1; place <= n; ++place)
481 {
482 SCOPED_TRACE(testing::Message() << "left " << left << ", checked " << checked
483 << ", n " << n << ", place " << place);
484 Husk::left = left;
485 Calls calls, old_calls;
486 Husk_Heap heap(n + 2, Husk_Less{&calls});
487 Old_Heap_Of<Husk> old{.cmp = Husk_Less{&old_calls}};
488 for (int k = 1; k <= n; ++k)
489 {
490 const Husk x(k % 3, k);
491 heap.insert(x);
492 old.insert(x);
493 }
494 ASSERT_EQ(layout(heap), old.layout());
495
496 if (checked)
497 heap.insert(std::move(heap[place]));
498 else
499 heap.insert_ne(std::move(heap[place]));
500 old.a.resize(n + 2); // before the reference to one of its items
501 old.insert(std::move(old.a[place]));
502
503 EXPECT_EQ(calls.items, old_calls.items);
504 EXPECT_EQ(layout(heap), old.layout());
505 }
506}
507
508// If the comparison throws in that insertion, the key, one of the items of
509// the heap, takes back what was moved from it, and the heap is as it was
510TEST(ArrayHeapThrowingCompare, AKeyThatItsMoveChangesStaysInTheHeap)
511{
512 size_t failed = 0;
513 for (const int left : {-1, 99})
514 for (const bool checked : {false, true})
515 for (int n = 1; n <= 9; ++n)
516 for (int place = 1; place <= n; ++place)
517 for (size_t at = 1; ; ++at)
518 {
519 SCOPED_TRACE(testing::Message() << "left " << left << ", checked " << checked << ", n " << n
520 << ", place " << place << ", call " << at);
521 Husk::left = left;
522 Calls calls;
523 Husk_Heap heap(n + 2, Husk_Less{&calls});
524 for (int k = 1; k <= n; ++k)
525 heap.insert(Husk(k % 3, k));
526 const std::vector<Husk> before = layout(heap);
527 calls.throw_at = calls.count + at;
528 bool thrown = false;
529 try
530 {
531 if (checked)
532 heap.insert(std::move(heap[place]));
533 else
534 heap.insert_ne(std::move(heap[place]));
535 }
536 catch (const std::runtime_error &)
537 {
538 thrown = true;
539 }
540 calls.throw_at = 0;
541 if (not thrown)
542 break;
543 ++failed;
544 EXPECT_EQ(heap.size(), static_cast<size_t>(n));
545 EXPECT_EQ(layout(heap), before);
546 }
547 EXPECT_GT(failed, 100u);
548}
549
550// A heapsort whose comparison throws leaves in the array the items that it
551// had, in another order, and none of them moved from
552TEST(ArrayHeapThrowingCompare, AFailedHeapsortKeepsEveryItem)
553{
554 std::mt19937 rng(5);
555 std::uniform_int_distribution<int> values(0, 20);
556 size_t failed = 0;
557 for (const bool faster : {false, true})
558 for (size_t n = 0; n <= 24; ++n)
559 {
560 std::vector<Item> items;
561 for (size_t k = 0; k < n; ++k)
562 items.emplace_back(values(rng), static_cast<int>(k + 1));
563 for (size_t at = 1; ; ++at)
564 {
565 SCOPED_TRACE(testing::Message() << "faster " << faster << ", n " << n << ", call " << at);
566 std::vector<Item> a = items;
567 Calls calls;
568 calls.throw_at = at;
569 bool thrown = false;
570 try
571 {
572 if (faster)
573 faster_heapsort(a.data(), a.size(), Counted_Less{&calls});
574 else
575 heapsort(a.data(), a.size(), Counted_Less{&calls});
576 }
577 catch (const std::runtime_error &)
578 {
579 thrown = true;
580 }
581 // each item with its priority, whatever its place
582 std::vector<Item> by_id = a;
583 std::sort(by_id.begin(), by_id.end(),
584 [](const Item & x, const Item & y) { return x.id < y.id; });
585 EXPECT_EQ(by_id, items);
586 if (not thrown)
587 {
588 EXPECT_TRUE(std::is_sorted(a.begin(), a.end(),
589 [](const Item & x, const Item & y) { return x.pri < y.pri; }));
590 break;
591 }
592 ++failed;
593 }
594 }
595 EXPECT_GT(failed, 1000u);
596}
597
598namespace
599{
600 // A comparison that contradicts itself: each call gives what a generator
601 // of random bits says, whatever the items
602 struct Random_Less
603 {
604 std::mt19937 *rng;
605
606 bool operator()(const Item &, const Item &) const { return (*rng)() & 1; }
607 };
608}
609
610// With a comparison that contradicts itself the heap cannot be in order,
611// but it keeps its items after each operation, none lost, repeated or
612// moved from: the places that the operations find are always in the array
613TEST(ArrayHeapThrowingCompare, AComparisonThatContradictsItselfKeepsTheItems)
614{
615 std::mt19937 bits(99), rng(3);
616 ArrayHeap<Item, Random_Less> heap(160, Random_Less{&bits});
617 std::vector<int> ids; // of the items in the heap
618 size_t removals = 0, updates = 0;
619 for (int k = 0; k < 20000; ++k)
620 {
621 const unsigned op = heap.is_empty() ? 0 : rng() % 7;
622 if (op < 3 and heap.size() < 150) // small, so that looking at all of it is cheap
623 {
624 if (k % 2 == 0)
625 heap.insert(Item(k, k + 1));
626 else
627 heap.insert_ne(Item(k, k + 1));
628 ids.push_back(k + 1);
629 }
630 else if (op <= 3)
631 {
632 const Item min = heap.getMin();
633 const auto it = std::find(ids.begin(), ids.end(), min.id);
634 ASSERT_NE(it, ids.end()) << "operation " << k;
635 ids.erase(it);
636 }
637 else
638 {
639 const size_t i = 1 + rng() % heap.size();
640 if (op == 4)
641 {
642 const auto it = std::find(ids.begin(), ids.end(), heap[i].id);
643 ASSERT_NE(it, ids.end()) << "operation " << k;
644 ids.erase(it);
645 heap.remove(heap[i]);
646 ++removals;
647 }
648 else
649 {
650 heap.update(heap[i]);
651 ++updates;
652 }
653 }
654 ASSERT_EQ(heap.size(), ids.size()) << "operation " << k;
655 std::vector<int> now;
656 for (size_t i = 1; i <= heap.size(); ++i)
657 now.push_back(heap[i].id);
658 std::sort(now.begin(), now.end());
659 std::vector<int> sorted = ids;
660 std::sort(sorted.begin(), sorted.end());
661 ASSERT_EQ(now, sorted) << "operation " << k;
662 }
663 EXPECT_GT(removals, 1000u);
664 EXPECT_GT(updates, 1000u);
665}
666
667namespace
668{
669 // An item whose copies throw while `armed`, and whose moves never do; it
670 // counts its copies
671 struct Fragile
672 {
673 static inline bool armed = false;
674 static inline size_t copies = 0;
675
676 int pri = 0;
677
678 Fragile() = default;
679 Fragile(const int p) noexcept : pri(p) {}
680 Fragile(const Fragile & o) : pri(o.pri) { copied(); }
681 Fragile & operator=(const Fragile & o)
682 {
683 copied();
684 pri = o.pri;
685 return *this;
686 }
687 Fragile(Fragile &&) noexcept = default;
688 Fragile & operator=(Fragile &&) noexcept = default;
689
690 static void copied()
691 {
692 if (armed)
693 throw std::bad_alloc();
694 ++copies;
695 }
696
697 bool operator<(const Fragile & o) const noexcept { return pri < o.pri; }
698 };
699}
700
701// An insertion whose copy of the key throws leaves the heap as it was: the
702// item was counted before it was copied, so the heap had one item more,
703// which was whatever its array held. And getMin() copies nothing: it copied
704// the minimum, and then the last item over it after counting it out, so a
705// copy that threw there lost the last item
706TEST(ArrayHeapThrowingCompare, ACopyThatThrowsLeavesTheHeapAsItWas)
707{
708 ArrayHeap<Fragile> heap(8);
709 for (const int p : {5, 3, 8, 1})
710 heap.insert(Fragile(p));
711
712 const Fragile key(0);
713 Fragile::armed = true;
714 EXPECT_THROW(heap.insert(key), std::bad_alloc);
715 EXPECT_THROW(heap.insert_ne(key), std::bad_alloc);
716 EXPECT_EQ(heap.size(), 4u);
717 EXPECT_EQ(heap.top().pri, 1);
718
719 std::vector<int> out; // with the copies still armed
720 while (not heap.is_empty())
721 out.push_back(heap.getMin().pri);
722 Fragile::armed = false;
723 EXPECT_EQ(out, (std::vector<int>{1, 3, 5, 8}));
724
725 for (const int p : {5, 3, 8, 1})
726 heap.insert(Fragile(p));
727 Fragile::copies = 0;
728 (void) heap.getMin();
729 heap.remove(heap[2]);
730 EXPECT_EQ(Fragile::copies, 0u);
731}
732
733namespace
734{
735 // A comparison of items that says that it does not throw
736 struct Nothrow_Less
737 {
738 bool operator()(const Item & a, const Item & b) const noexcept { return a.pri < b.pri; }
739 };
740
741 // Orders shared pointers by what they point to; it may throw or not
742 template <bool nothrow>
743 struct Pointed_Less
744 {
745 bool operator()(const std::shared_ptr<int> & a, const std::shared_ptr<int> & b) const noexcept(nothrow)
746 {
747 return *a < *b;
748 }
749 };
750}
751
752// With a comparison that does not throw, remove() has nothing to undo and
753// moves the last item over the removed one, as before. The heap keeps the
754// other items, each one whole, and in order
755TEST(ArrayHeap, RemoveWithAComparisonThatDoesNotThrow)
756{
757 std::mt19937 rng(17);
758 std::uniform_int_distribution<int> values(0, 50);
760 std::vector<int> ids;
761 size_t removals = 0;
762 for (int k = 0; k < 6000; ++k)
763 {
764 if (heap.size() < 2 or (rng() % 2 == 0 and heap.size() < 290))
765 {
766 heap.insert(Item(values(rng), k + 1));
767 ids.push_back(k + 1);
768 }
769 else
770 {
771 const size_t i = 1 + rng() % heap.size();
772 ids.erase(std::find(ids.begin(), ids.end(), heap[i].id));
773 heap.remove(heap[i]);
774 ++removals;
775 }
776 std::vector<int> now;
777 for (size_t i = 1; i <= heap.size(); ++i)
778 now.push_back(heap[i].id);
779 std::sort(now.begin(), now.end());
780 std::vector<int> sorted = ids;
781 std::sort(sorted.begin(), sorted.end());
782 ASSERT_EQ(now, sorted) << "operation " << k;
783 Nothrow_Less less;
784 ASSERT_TRUE(valid_heap(&heap[0], 1, heap.size(), less)) << "operation " << k;
785 }
786 EXPECT_GT(removals, 2000u);
787}
788
789// As before, an item that remove() takes out from among the others holds
790// nothing afterwards, whether the comparison may throw or not: the heap does
791// not keep it alive in the entry that it no longer counts. The last item of
792// the array, which is removed without moving anything, stays in its entry
793// until another one takes it
794TEST(ArrayHeap, RemoveReleasesTheItem)
795{
796 auto check = [](auto & heap)
797 {
798 std::vector<std::weak_ptr<int>> seen;
799 for (const int v : {5, 3, 8, 1, 9, 2})
800 {
801 auto p = std::make_shared<int>(v);
802 seen.push_back(p);
803 heap.insert(std::move(p));
804 }
805 const std::weak_ptr<int> second = heap[2];
806 heap.remove(heap[2]); // not the last one
807 const auto alive_of = [&seen]
808 {
809 return std::count_if(seen.begin(), seen.end(), [](const auto & w) { return not w.expired(); });
810 };
811 EXPECT_TRUE(second.expired()); // that one, and no other
812 EXPECT_EQ(alive_of(), 5);
813 heap.remove(heap[heap.size()]); // the last one
814 EXPECT_EQ(alive_of(), 5);
815 EXPECT_EQ(heap.size(), 4u);
816 size_t in_heap = 0;
817 for (size_t i = 1; i <= heap.size(); ++i)
818 in_heap += heap[i] != nullptr ? 1 : 0;
819 EXPECT_EQ(in_heap, 4u);
820 };
821 ArrayHeap<std::shared_ptr<int>, Pointed_Less<true>> quiet(8);
822 check(quiet);
823 ArrayHeap<std::shared_ptr<int>, Pointed_Less<false>> loud(8);
824 check(loud);
825}
826
827// The heapsorts moved their pointer one item back before they looked at the
828// size. With nothing to sort the pointer may be null, as that of an empty
829// vector, and moving a null pointer is undefined
830TEST(ArrayHeap, HeapsortOfNothingAndOfOneItem)
831{
832 heapsort<int>(nullptr, 0);
833 faster_heapsort<int>(nullptr, 0);
834 std::vector<int> none;
835 heapsort(none.data(), none.size());
836 faster_heapsort(none.data(), none.size());
837 int one = 7;
838 heapsort(&one, 1);
839 EXPECT_EQ(one, 7);
840 faster_heapsort(&one, 1);
841 EXPECT_EQ(one, 7);
842 std::vector<int> two{2, 1};
843 heapsort(two.data(), two.size());
844 EXPECT_EQ(two, (std::vector<int>{1, 2}));
845 two = {2, 1};
846 faster_heapsort(two.data(), two.size());
847 EXPECT_EQ(two, (std::vector<int>{1, 2}));
848}
849
850// The heapsorts number the items from 1, and took them through a pointer to
851// one item before the array, which may not be formed. They take them now
852// through From_One, whose items a constant expression gives: there, a
853// pointer out of the array does not compile
854namespace
855{
856 struct Constant_Less
857 {
858 constexpr bool operator () (const int & a, const int & b) const noexcept { return a < b; }
859 };
860
861 // The two heapsorts of eight items in a constant expression. There, a
862 // pointer to an entry before the array is an error that the compiler
863 // sees, and no sanitizer sees it in the program that runs
864 constexpr bool the_heapsorts_sort()
865 {
866 int a[] = {5, 3, 8, 1, 9, 2, 7, 3};
867 int b[] = {5, 3, 8, 1, 9, 2, 7, 3};
868 heapsort(a, 8, Constant_Less());
869 faster_heapsort(b, 8, Constant_Less());
870 for (int i = 1; i < 8; ++i)
871 if (a[i - 1] > a[i] or b[i - 1] > b[i])
872 return false;
873 return a[0] == 1 and a[7] == 9 and b[0] == 1 and b[7] == 9;
874 }
875 static_assert(the_heapsorts_sort());
876}
877
878TEST(ArrayHeap, TheHeapsortsTakeTheItemsFromOneInsideTheArray)
879{
880 static constexpr int three[] = {10, 20, 30};
881 static_assert(arrayheap_detail::From_One<const int>{three}[1] == 10);
882 static_assert(arrayheap_detail::From_One<const int>{three}[3] == 30);
883 static_assert(&arrayheap_detail::From_One<const int>{three}[2] == three + 1);
884
885 // each count of items from 2 to 70, with items that repeat. The state
886 // has 64 bits wherever it is compiled: the items come from its high
887 // bits, and a long has 32 on Windows
888 std::uint64_t x = 20261125;
889 for (size_t n = 2; n <= 70; ++n)
890 for (int trial = 0; trial < 4; ++trial)
891 {
892 Array<int> items(n, 0), counts(16, 0);
893 for (size_t i = 0; i < n; ++i)
894 {
895 x = x * 6364136223846793005ULL + 1442695040888963407ULL;
896 items(i) = static_cast<int>((x >> 33) % 16);
897 ++counts(static_cast<size_t>(items(i)));
898 }
899 Array<int> other = items;
900 heapsort(&items(0), n);
901 faster_heapsort(&other(0), n);
902 Array<int> sorted;
903 for (int v = 0; v < 16; ++v)
904 for (int k = 0; k < counts(static_cast<size_t>(v)); ++k)
905 sorted.append(v);
906 ASSERT_EQ(items, sorted) << n << " items, trial " << trial;
907 ASSERT_EQ(other, sorted) << n << " items, trial " << trial;
908 }
909}
910
911namespace
912{
913 // What a comparison returns. Its implicit conversion to bool does not
914 // throw; the explicit one, which a condition chooses for a result that
915 // has no name, may
916 struct Sly_Bool
917 {
918 bool value;
919 long *conversions; // those of the conditions, so far
920 long throw_at; // the one that throws (0: none)
921
922 operator bool() const & noexcept { return value; }
923
924 explicit operator bool() &&
925 {
926 if (++*conversions == throw_at)
927 throw std::runtime_error("conversion");
928 return value;
929 }
930 };
931
932 // A comparison that does not throw. For two items that are not const, as
933 // a heap compares its own, the conversion of its result in a condition may
934 struct Sly_Less
935 {
936 long *conversions;
937 long *throw_at;
938
939 bool operator()(const int & a, const int & b) const noexcept { return a < b; }
940
941 Sly_Bool operator()(int & a, int & b) const noexcept { return {a < b, conversions, *throw_at}; }
942 };
943
944 static_assert(std::is_nothrow_invocable_r_v<bool, Sly_Less &, int &, int &>);
945 static_assert(not noexcept(static_cast<bool>(std::declval<Sly_Less &>()(std::declval<int &>(),
946 std::declval<int &>()))));
947}
948
949// remove() takes the way that has nothing to undo only if the comparison
950// cannot throw, with the conversion to bool that the conditions of the
951// sifts make of its result. It asked whether the implicit conversion could
952// throw, which may be another function: with this comparison it lost the
953// item that it took out
954TEST(ArrayHeapThrowingCompare, AConversionInAConditionThatThrowsIsUndone)
955{
956 size_t failed = 0;
957 for (size_t i = 1; i <= 5; ++i)
958 for (long at = 1; ; ++at)
959 {
960 SCOPED_TRACE(testing::Message() << "item " << i << ", conversion " << at);
961 long conversions = 0, throw_at = 0;
962 ArrayHeap<int, Sly_Less> heap(8, Sly_Less{&conversions, &throw_at});
963 for (const int v : {1, 2, 3, 4, 5, 6})
964 heap.insert(v);
965 const auto items_of = [&heap]
966 {
967 std::vector<int> items;
968 for (size_t k = 1; k <= heap.size(); ++k)
969 items.push_back(heap[k]);
970 return items;
971 };
972 const std::vector<int> before = items_of();
973 conversions = 0;
974 throw_at = at;
975 bool thrown = false;
976 try
977 {
978 heap.remove(heap[i]);
979 }
980 catch (const std::runtime_error &)
981 {
982 thrown = true;
983 }
984 throw_at = 0;
985 if (not thrown)
986 {
987 EXPECT_EQ(heap.size(), 5u);
988 std::vector<int> left = items_of(), expected = before;
989 expected.erase(expected.begin() + static_cast<long>(i - 1));
990 std::sort(left.begin(), left.end());
991 std::sort(expected.begin(), expected.end());
992 EXPECT_EQ(left, expected);
993 break;
994 }
995 ++failed;
996 EXPECT_EQ(items_of(), before);
997 }
998 EXPECT_GT(failed, 5u);
999}
1000
1001namespace
1002{
1003 // An item that has no default constructor, and holds something that
1004 // tells whether it is alive
1005 struct Rooted
1006 {
1007 int pri;
1008 int id;
1009 std::shared_ptr<int> held;
1010
1011 Rooted() = delete;
1012 Rooted(const int p, const int i) : pri(p), id(i), held(std::make_shared<int>(i)) {}
1013 };
1014
1015 struct Rooted_Nothrow_Less
1016 {
1017 bool operator()(const Rooted & a, const Rooted & b) const noexcept { return a.pri < b.pri; }
1018 };
1019
1020 // The six items of a test in a heap over a buffer, whose entry 0 a heap
1021 // does not use, and what tells whether each one is alive
1022 template <class Heap>
1023 std::vector<std::weak_ptr<int>> fill_rooted(Heap & heap)
1024 {
1025 std::vector<std::weak_ptr<int>> seen;
1026 int id = 0;
1027 for (const int v : {5, 3, 8, 1, 9, 2})
1028 {
1029 Rooted item(v, ++id);
1030 seen.push_back(item.held);
1031 heap.insert(std::move(item));
1032 }
1033 return seen;
1034 }
1035
1036 size_t alive_of(const std::vector<std::weak_ptr<int>> & seen)
1037 {
1038 return static_cast<size_t>(std::count_if(seen.begin(), seen.end(),
1039 [](const auto & w) { return not w.expired(); }));
1040 }
1041
1042 // The priority and the identity of each item of a heap, in the order of
1043 // its array: no copy of the items, which would keep alive what they hold
1044 template <class Heap>
1045 std::vector<std::pair<int, int>> rooted_in(const Heap & heap)
1046 {
1047 std::vector<std::pair<int, int>> items;
1048 for (size_t i = 1; i <= heap.size(); ++i)
1049 items.emplace_back(heap[i].pri, heap[i].id);
1050 return items;
1051 }
1052}
1053
1054// A heap over a buffer of its caller takes items that have no default
1055// constructor, and remove() worked with them. It stopped compiling, since
1056// it built an empty item for the entry of the one that it takes out. Now
1057// it builds none with a comparison that cannot throw, and with one that
1058// may it takes the item out of its entry by a move where it cannot build
1059// an empty one
1060TEST(ArrayHeap, RemoveNeedsNoDefaultConstructor)
1061{
1062 {
1063 std::vector<Rooted> buffer(8, Rooted(0, 0));
1064 ArrayHeap<Rooted, Rooted_Nothrow_Less> heap(buffer.data(), 7);
1065 const auto seen = fill_rooted(heap);
1066 heap.remove(heap[2]); // not the last one
1067 EXPECT_EQ(heap.size(), 5u);
1068 EXPECT_EQ(alive_of(seen), 5u);
1069 int last = 0;
1070 while (not heap.is_empty())
1071 {
1072 const Rooted min = heap.getMin();
1073 EXPECT_LE(last, min.pri);
1074 last = min.pri;
1075 }
1076 }
1077
1078 // with a comparison that may throw, at each of its calls in turn
1079 size_t failed = 0;
1080 for (size_t i = 1; i <= 5; ++i)
1081 for (size_t at = 1; ; ++at)
1082 {
1083 SCOPED_TRACE(testing::Message() << "item " << i << ", call " << at);
1084 std::vector<Rooted> buffer(8, Rooted(0, 0));
1085 Calls calls;
1086 ArrayHeap<Rooted, Counted_Less_Of<Rooted>> heap(buffer.data(), 7, Counted_Less_Of<Rooted>{&calls});
1087 const auto seen = fill_rooted(heap);
1088 const auto before = rooted_in(heap);
1089 calls.throw_at = calls.count + at;
1090 bool thrown = false;
1091 try
1092 {
1093 heap.remove(heap[i]);
1094 }
1095 catch (const std::runtime_error &)
1096 {
1097 thrown = true;
1098 }
1099 calls.throw_at = 0;
1100 if (not thrown)
1101 {
1102 EXPECT_EQ(heap.size(), 5u);
1103 EXPECT_EQ(alive_of(seen), 5u); // the one that left holds nothing
1104 break;
1105 }
1106 ++failed;
1107 EXPECT_EQ(rooted_in(heap), before);
1108 EXPECT_EQ(alive_of(seen), 6u);
1109 }
1110 EXPECT_GT(failed, 5u);
1111}
1112
1113namespace
1114{
1115 // An item whose default constructor throws when it is told to
1116 struct Touchy
1117 {
1118 static inline bool armed = false;
1119 static inline long built = 0; // by default
1120
1121 int pri = 0;
1122 int id = 0;
1123
1124 Touchy()
1125 {
1126 ++built;
1127 if (armed)
1128 throw std::runtime_error("default constructor");
1129 }
1130
1131 Touchy(const int p, const int i) noexcept : pri(p), id(i) {}
1132 };
1133
1134 struct Touchy_Nothrow_Less
1135 {
1136 bool operator()(const Touchy & a, const Touchy & b) const noexcept { return a.pri < b.pri; }
1137 };
1138}
1139
1140// With a comparison that may throw, remove() built an empty item for the
1141// entry of the one that it takes out, once that one was out: if the
1142// default constructor threw, the exception came out of a heap that had
1143// lost the item. Now it builds an item only if building it cannot throw,
1144// and none with a comparison that cannot throw
1145TEST(ArrayHeapThrowingCompare, RemoveBuildsNoItemWhoseConstructorMayThrow)
1146{
1147 static_assert(not std::is_nothrow_default_constructible_v<Touchy>);
1148 Calls calls;
1149 ArrayHeap<Touchy, Counted_Less_Of<Touchy>> heap(8, Counted_Less_Of<Touchy>{&calls});
1151 int id = 0;
1152 for (const int v : {5, 3, 8, 1, 9, 2})
1153 {
1154 heap.insert(Touchy(v, ++id));
1155 quiet.insert(Touchy(v, id));
1156 }
1157
1158 const long built = Touchy::built;
1159 Touchy::armed = true;
1160 EXPECT_NO_THROW(heap.remove(heap[2]));
1161 EXPECT_NO_THROW(quiet.remove(quiet[2]));
1162 Touchy::armed = false;
1163 EXPECT_EQ(Touchy::built, built);
1164 EXPECT_EQ(heap.size(), 5u);
1165 EXPECT_EQ(quiet.size(), 5u);
1166 int last = 0;
1167 while (not heap.is_empty())
1168 {
1169 const Touchy min = heap.getMin();
1170 EXPECT_LE(last, min.pri);
1171 last = min.pri;
1172 }
1173}
1174
1175namespace
1176{
1177 // An item whose default constructor does not throw and whose move
1178 // assignment throws when its source is empty, as no item of a heap is.
1179 // A move leaves its source empty
1180 struct Fussy
1181 {
1182 int pri = 0;
1183 int id = 0; // none: empty
1184
1185 Fussy() noexcept = default;
1186 Fussy(const int p, const int i) noexcept : pri(p), id(i) {}
1187 Fussy(const Fussy &) = default;
1188 Fussy & operator=(const Fussy &) = default;
1189 Fussy(Fussy && o) noexcept : pri(o.pri), id(std::exchange(o.id, 0)) {}
1190
1191 Fussy & operator=(Fussy && o)
1192 {
1193 if (o.id == 0)
1194 throw std::runtime_error("move assignment from an empty item");
1195 pri = o.pri;
1196 id = std::exchange(o.id, 0);
1197 return *this;
1198 }
1199 };
1200
1201 // The identities, in order, of the items that a heap gives, which must
1202 // come by priority: pri_and_id gives the two of an item
1203 template <class Heap, class Pri_And_Id>
1204 std::vector<int> drained_ids(Heap & heap, Pri_And_Id pri_and_id)
1205 {
1206 std::vector<int> ids;
1207 int last = 0;
1208 while (not heap.is_empty())
1209 {
1210 const auto min = heap.getMin();
1211 const std::pair<int, int> item = pri_and_id(min);
1212 EXPECT_LE(last, item.first);
1213 last = item.first;
1214 ids.push_back(item.second);
1215 }
1216 std::sort(ids.begin(), ids.end());
1217 return ids;
1218 }
1219
1220 // The identities from 1 to n but one
1221 std::vector<int> all_but(const int n, const int out)
1222 {
1223 std::vector<int> ids;
1224 for (int i = 1; i <= n; ++i)
1225 if (i != out)
1226 ids.push_back(i);
1227 return ids;
1228 }
1229}
1230
1231// With a comparison that may throw, remove() emptied the entry of the item
1232// that it takes out by assigning an empty item to it, once that one was
1233// out: if the assignment threw, the exception came out of a heap that had
1234// lost the item, where trying again with the same reference took another
1235// one out. Now nothing that may throw runs once the item is out: such an
1236// item is moved out of its entry
1237TEST(ArrayHeapThrowingCompare, RemoveAssignsNoEmptyItemIfThatMayThrow)
1238{
1239 static_assert(std::is_nothrow_default_constructible_v<Fussy>);
1240 static_assert(not std::is_nothrow_move_assignable_v<Fussy>);
1241 static_assert(std::is_nothrow_move_constructible_v<Fussy>);
1242 std::vector<Fussy> buffer(8);
1243 Calls calls;
1244 ArrayHeap<Fussy, Counted_Less_Of<Fussy>> heap(buffer.data(), 7, Counted_Less_Of<Fussy>{&calls});
1245 int id = 0;
1246 for (const int v : {5, 3, 8, 1, 9, 2})
1247 heap.insert(Fussy(v, ++id));
1248 const int removed = heap[2].id;
1249 ASSERT_NE(removed, 0);
1250
1251 EXPECT_NO_THROW(heap.remove(heap[2]));
1252 EXPECT_EQ(heap.size(), 5u);
1253 EXPECT_EQ(buffer[6].id, 0); // the entry of the item that left, past the end
1254 EXPECT_EQ(drained_ids(heap, [](const Fussy & x) { return std::make_pair(x.pri, x.id); }),
1255 all_but(6, removed));
1256}
1257
1258namespace
1259{
1260 // The part of an item that the standard library exchanges by its own
1261 // swap, with no move, and whose default and move constructors throw when
1262 // they are told to. It holds something that tells whether it is alive
1263 struct Welded
1264 {
1265 static inline bool armed = false;
1266
1267 int pri = 0;
1268 int id = 0;
1269 std::shared_ptr<int> held;
1270
1271 Welded()
1272 {
1273 if (armed)
1274 throw std::runtime_error("default constructor");
1275 }
1276
1277 Welded(const int p, const int i) : pri(p), id(i), held(std::make_shared<int>(i)) {}
1278 Welded(const Welded &) = default;
1279 Welded & operator=(const Welded &) = default;
1280
1281 Welded(Welded && o) : pri(o.pri), id(o.id), held(o.held)
1282 {
1283 if (armed)
1284 throw std::runtime_error("move constructor");
1285 }
1286
1287 Welded & operator=(Welded &&) noexcept = default;
1288
1289 friend void swap(Welded & a, Welded & b) noexcept
1290 {
1291 std::swap(a.pri, b.pri);
1292 std::swap(a.id, b.id);
1293 a.held.swap(b.held);
1294 }
1295 };
1296
1297 // std::swap() of a pair calls the swap of each of its members: this item
1298 // is exchanged with no move, as a std::deque is, whose move constructor
1299 // may throw in some standard libraries
1300 using Welded_Item = std::pair<Welded, int>;
1301
1302 struct Welded_Less
1303 {
1304 bool operator()(const Welded_Item & a, const Welded_Item & b) const // may throw
1305 {
1306 return a.first.pri < b.first.pri;
1307 }
1308 };
1309}
1310
1311// With a comparison that may throw and an item that it could not empty
1312// otherwise, remove() moved the item out of its entry once it was out of
1313// the heap: if the move constructor threw, the exception came out of a
1314// heap that had lost the item. An exchange that does not throw, which is
1315// what the heap asks of its items, does not mean a move that does not. Now
1316// such an item stays in its entry until another one takes it
1317TEST(ArrayHeapThrowingCompare, RemoveMovesNoItemOutIfThatMayThrow)
1318{
1319 static_assert(noexcept(std::swap(std::declval<Welded_Item &>(), std::declval<Welded_Item &>())));
1320 static_assert(not std::is_nothrow_default_constructible_v<Welded_Item>);
1321 static_assert(not std::is_nothrow_move_constructible_v<Welded_Item>);
1322 std::vector<Welded_Item> buffer(8);
1323 ArrayHeap<Welded_Item, Welded_Less> heap(buffer.data(), 7);
1324 std::vector<std::weak_ptr<int>> seen;
1325 int id = 0;
1326 for (const int v : {5, 3, 8, 1, 9, 2})
1327 {
1328 Welded_Item item(Welded(v, ++id), v);
1329 seen.push_back(item.first.held);
1330 heap.insert(std::move(item));
1331 }
1332 const int removed = heap[2].first.id;
1333
1334 Welded::armed = true;
1335 EXPECT_NO_THROW(heap.remove(heap[2]));
1336 Welded::armed = false;
1337 EXPECT_EQ(heap.size(), 5u);
1338 EXPECT_EQ(buffer[6].first.id, removed); // in its entry, which is past the end
1339 EXPECT_EQ(alive_of(seen), 6u);
1340
1341 Welded_Item seventh(Welded(4, ++id), 4);
1342 seen.push_back(seventh.first.held);
1343 heap.insert(std::move(seventh)); // takes that entry
1344 EXPECT_EQ(alive_of(seen), 6u);
1345 EXPECT_TRUE(seen[static_cast<size_t>(removed) - 1].expired());
1346 EXPECT_EQ(drained_ids(heap, [](const Welded_Item & x) { return std::make_pair(x.first.pri, x.first.id); }),
1347 all_but(7, removed));
1348}
bool operator<(const Time &l, const Time &r)
Definition ah-time.H:143
void PrintTo(const mpq_class &q, std::ostream *os)
#define X(p)
Definition btreepic.C:374
long double h
Definition btreepic.C:154
long double w
Definition btreepic.C:153
size_t size_t int32_t value
Definition ca-c-api.h:116
size_t size_t int32_t * out
Definition ca-c-api.h:120
Fixed-capacity binary heap backed by a raw array.
T & insert(const T &key)
Insert an element into the heap.
T & insert_ne(const T &key)
Insert an element without checking capacity.
T getMax()
See getMin().
T getMin()
Remove the smallest element in the heap and return a copy of its value.
constexpr bool is_empty() const noexcept
Return true if the heap is empty.
void update(T &data)
Update the priority of an element stored in the heap.
T get()
See getMin().
T & top()
Return a mutable reference to the minimum element.
constexpr size_t size() const noexcept
Return the number of elements currently stored.
void remove(T &item)
Remove an element from the heap given a reference to it.
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
T & append(const T &data)
Append a copy of data
Definition tpl_array.H:331
Minimal std::expected-style result type for C++20.
iterator end() noexcept
Return an STL-compatible end iterator.
iterator begin() noexcept
Return an STL-compatible iterator to the first element.
#define TEST(name)
static mt19937 rng
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_min_function > > min(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4189
int cmp(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4196
static mpfr_t y
Definition mpfr_mul_d.c:3
Main namespace for Aleph-w library functions.
void sift_down_up(T *ptr, const size_t l, const size_t i, const size_t r, Compare &cmp)
Restore the heap property by sifting down and then sifting up.
bool operator==(const DynList< T > &l1, const DynList< T > &l2)
Equality operator for DynList.
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.
T & swap(T &t1, T &t2)
Generic swap using object's swap method.
Definition ahTypes.H:123
constexpr Bit_Column bits(const unsigned n)
Column of n bits without sign: the integers of [0, 2^n - 1].
bool valid_heap(T *array, const size_t l, const size_t r, const Compare &cmp=Compare())
Check whether a range satisfies the heap property.
and
Check uniqueness with explicit hash + equality functors.
Fw_Itor remove(Fw_Itor __first, const Fw_Itor &__last, const T &__value)
Remove elements equal to a value.
Definition ahAlgo.H:962
constexpr void faster_heapsort(T *array, const size_t n, const Compare &cmp=Compare())
Optimized version of heapsort.
constexpr void heapsort(T *array, const size_t n, const Compare &cmp=Compare())
Sort an array using the heapsort algorithm.
bool none(const Container &container, Operation &operation)
Return true if no element satisfies operation.
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.
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
STL namespace.
The items of an array, numbered from 1.
bool check(GT &g)
static int * k
Gsl_Compatible_Rng r
Fixed-capacity binary heap and heapsort algorithms.
Dynamic array container with automatic resizing.
DynList< int > l