MinHeap
MinHeap: A Min Priority Queue implemented as a Thin Wrapper around [BinaryHeap<Reverse<T>>] from the standard library.
Quickstart
Add min_heap as a dependency: run cargo add min_heap, or add the following to your Cargo.toml file.
[]
= "1.0"
min_heap::MinHeap mirrors the API of std::collections::BinaryHeap; here is an overview of what you can do with it.
use MinHeap;
// Type inference lets us omit an explicit type signature (which
// would be `MinHeap<i32>` in this example).
let mut heap = new;
// We can use peek to look at the smallest item in the heap. In this case,
// there's no items in there yet so we get None.
assert_eq!;
// Let's add some numbers...
heap.push;
heap.push;
heap.push;
// Now peek shows the smallest item in the heap.
assert_eq!;
// We can check the length of a heap.
assert_eq!;
// We can iterate over the items in the heap, although they are returned in
// an unspecified order.
for x in &heap
// If we instead pop these scores, they should come back in order.
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
// We can clear the heap of any remaining items.
heap.clear;
// The heap should now be empty.
assert!
When to use MinHeap?
By default, the BinaryHeap struct from std::collections is a max-heap, i.e. it provides efficient access and update to the largest element in a collection.
To use it as a min-heap, one can either use core::cmp::Reverse or a custom Ord implementation, but this usually adds a lot of boilerplate to your code. This crate implements this boilerplate so that you never have to write it yourself again! It also allows you to use the derived Ord implementation instead of manually reversing it.
Here is a comparison of code without and with min_heap::MinHeap.
Reverse
// Without `MinHeap`
let mut heap = new;
heap.push;
heap.push;
heap.push;
if let Some = heap.pop
let heap_items: = heap.into_iter.map.collect;
// With `MinHeap`
let mut heap = new;
heap.push;
heap.push;
heap.push;
if let Some = heap.pop
let heap_items: = heap.into_iter.collect;
Custom Ord implementation
// Without `MinHeap`
// The priority queue depends on `Ord`.
// Explicitly implement the trait so the queue becomes a min-heap
// instead of a max-heap.
// `PartialOrd` needs to be implemented as well.
// With `MinHeap`: we can use the derived implementation!
Comparison with other min-heap crates
All other popular crates that provide min-heaps implementations are forks or reimplementations of BinaryHeap from the standard library, and some of them are no longer maintained. This crate provides a wrapper around the battle-tested BinaryHeap from std::collections, therefore it benefits from its updates and bug fixes.
Missing features
The unstable (nightly) features of BinaryHeap, such as the allocator API, are not available (yet!) in min_heap.