BTreeMap Iterates In Sorted Key Order
Iterate a BTreeMap and get keys in ascending order every run, so reports and diffs are deterministic without collecting and sorting first.
Code
use std::collections::BTreeMap;
fn main() {
let mut inventory = BTreeMap::new();
inventory.insert("magnet", 40);
inventory.insert("bolt", 120);
inventory.insert("washer", 75);
// BTreeMap 按键有序迭代:输出与插入顺序无关
for (part, count) in &inventory {
println!("{part}: {count}");
}
// 有序性让首尾元素都是 O(log n) 操作
println!("first: {:?}", inventory.iter().next());
println!("last: {:?}", inventory.iter().next_back());
// range:只遍历字典序区间,中间键不用全扫
for (part, count) in inventory.range("bolt".."magnet") {
println!("in range {part}: {count}");
}
// 相比 HashMap:需要确定性输出时选 BTreeMap
println!("keys sorted: {:?}", inventory.keys().collect::<Vec<_>>());
}How it works
BTreeMap Iterates In Sorted Key Order is built around the function main.
Iteration happens inside for (part, count) in &inventory — everything outside it runs once.
Using it
Running the file prints labeled results such as first:, last:, in range — each operation’s effect is visible in the output.
Key statements
let mut inventory = BTreeMap::new();
inventory.insert("magnet", 40);
inventory.insert("washer", 75);
Interactive Tools for This Topic
FAQ
- What does BTreeMap Iterates In Sorted Key Order print when run?
- No setup needed: run the file and look for labeled lines like `first:`, `last:`, `in range` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.