Heap Iter Order Is Not Sorted
BinaryHeap::iter() walks internal heap layout rather than sorted order, so ordered consumption needs peek or an explicit into_sorted_vec.
Code
use std::collections::BinaryHeap;
fn main() {
let mut heap = BinaryHeap::new();
for score in [64, 87, 91, 43, 79] {
heap.push(score);
}
// peek 是堆顶最大值,但 iter() 按内部数组布局走,输出不是有序的
println!("peek: {:?}", heap.peek());
println!("iter view: {:?}", heap.iter().collect::<Vec<_>>());
// 有序消费必须显式转换:into_sorted_vec 升序弹空堆
println!("sorted: {:?}", heap.into_sorted_vec());
}What the file does
All of the logic lives in the function main.
Repetition is confined to for score in [64, 87, 91, 43, 79] — the rest of the file is straight-line.
What to watch for
- Nothing to vet in a supply-chain review — the file pulls in no packages.
Using it
Entry signature: fn main()
The run emits 3 labeled sections — peek:, iter view:, sorted: — one per step.
Key statements
let mut heap = BinaryHeap::new();
heap.push(score);
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 Heap Iter Order Is Not Sorted print when run?
- No setup needed: run the file and look for labeled lines like `peek:`, `iter view:`, `sorted:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.