实现说明
BTreeMap 有序快照报表的核心是函数 main。
重复被限制在 for path in ["/b", "/a", "/c", "/a", "/b", "/a"] 里——其余代码按顺序各跑一遍。
使用要点
- 直接运行文件,输出会带上标签,比如
a..d entries:、total——输出的每一行都能指回产生它的那次调用。
常见问题
运行「BTreeMap 有序快照报表」会打印什么?
运行文件本身,a..d entries:、total 这些前缀各对应一段演示逻辑。
核心语句
total += count;
.map(|(k, v)| (k.clone(), *v))
.collect();
代码示例
use std::collections::BTreeMap;
fn main() {
// BTreeMap keeps keys sorted:遍历天然按键序,快照报表无需再排序
let mut hits: BTreeMap<String, u32> = BTreeMap::new();
for path in ["/b", "/a", "/c", "/a", "/b", "/a"] {
*hits.entry(path.to_string()).or_insert(0) += 1;
}
// 范围迭代:只取 a..d 之间的路径,仍保持有序
let within: Vec<(String, u32)> = hits
.range("a".to_string().."d".to_string())
.map(|(k, v)| (k.clone(), *v))
.collect();
println!("a..d entries: {:?}", within);
// 全量快照输出:顺序稳定,可直接做 golden 对比
let mut total = 0;
for (path, count) in &hits {
println!("{} {}", count, path);
total += count;
}
println!("total {}", total);
}