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.

RustData Integrity

Code

rustsnippet
15 lines
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

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.