How to Use BinaryHeap (Priority Queue) in Rust

Use std::collections::BinaryHeap to efficiently manage a priority queue that automatically keeps the highest priority element accessible in constant time.

Use std::collections::BinaryHeap to manage a priority queue where the largest element is always at the top.

use std::collections::BinaryHeap;

fn main() {
    let mut heap = BinaryHeap::new();
    heap.push(3);
    heap.push(1);
    heap.push(4);
    
    // Pop returns the largest element first (4, then 3, then 1)
    while let Some(val) = heap.pop() {
        println!("{}", val);
    }
}

Note: BinaryHeap is a max-heap by default. To create a min-heap, wrap your items in a custom struct implementing Ord that reverses the comparison logic.