BinaryHeap into_sorted_vec Ordered Drain

BinaryHeap::into_sorted_vec drains every element in ascending order and leaves the heap empty, replacing manual repeated pops.

RustData Integrity

Code

rustsnippet
20 lines
use std::cmp::Reverse;
use std::collections::BinaryHeap;

fn main() {
    let mut heap = BinaryHeap::from(vec![7, 1, 9, 3, 5]);
    println!("peek max: {:?}", heap.peek());

    // into_sorted_vec: fully ordered drain, ascending — the heap is consumed
    let ascending = heap.into_sorted_vec();
    println!("ascending: {ascending:?}");
    println!("sorted len: {}", ascending.len());

    // a min-heap of Reverse drains largest-first
    let mut mins = BinaryHeap::new();
    for score in [40, 90, 65] {
        mins.push(Reverse(score));
    }
    let descending: Vec<i32> = mins.into_sorted_vec().into_iter().map(|r| r.0).collect();
    println!("descending: {descending:?}");
}

How the snippet works

The part worth importing is the function main — everything else is wiring.

The cycling part of this snippet is for score in [40, 90, 65].

Points of care

  • The third-party count is zero; the runtime already has every API used here.

Applying it

Entry signature: fn main()

The file’s output announces each step as it happens: peek max:, ascending:, sorted len:.

Statements that matter most here

let descending: Vec<i32> = mins.into_sorted_vec().into_iter().map(|r| r.0).collect();

Interactive Tools for This Topic

FAQ

What does BinaryHeap into_sorted_vec Ordered Drain print when run?
Running the file directly is enough — expect labeled output lines such as `peek max:`, `ascending:`, `sorted len:`.