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.
Code
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
JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.