On this page
BinaryHeap
Prev: `VecDeque` | Up: collections | Next: smart_pointers
Rel: collections, rust/builtins
Ref: Rust std — BinaryHeap
Tags: #public #prog #rust #stdlib #collections #tier/standard
Signature & Overview
BinaryHeap<T>
Array-backed max-heap priority queue ($O(\log n)$ push/pop, $O(1)$ peek).
Notes & Pitfalls
- Max-heap by default:
.pop()returns the largest element; wrap elements instd::cmp::Reverse(x)for a min-heap. - Iterating
.iter()is NOT sorted: Drain withwhile let Some(v) = heap.pop()or call.into_sorted_vec().
Example
use std::cmp::Reverse;
use std::collections::BinaryHeap;
fn main() {
let mut min_heap = BinaryHeap::from([Reverse(30), Reverse(10), Reverse(20)]);
assert_eq!(min_heap.pop(), Some(Reverse(10)));
assert_eq!(min_heap.pop(), Some(Reverse(20)));
}
Linked from
Related notes
- tuts/rust/std/collections/VecDeque Linked here; links to this page; shared tags: #collections, #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections Linked here; links to this page; shared tags: #collections, #prog, #rust, #stdlib
- tuts/rust/std/smart_pointers Linked here; shared tags: #prog, #rust, #stdlib
- tuts/rust/builtins Linked here; shared tags: #prog, #rust
- tuts/rust/std/collections/BTreeMap shared tags: #collections, #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/HashMap shared tags: #collections, #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/HashSet shared tags: #collections, #prog, #rust, #stdlib, #tier
- tuts/rust/std/error_and_fmt/Display shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/error_and_fmt/Error shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/error_and_fmt/format shared tags: #prog, #rust, #stdlib, #tier