实现说明
用 BTreeMap::range 按边界切片时间桶的核心是函数 main。
使用要点
- 零第三方依赖——用到的每个 API 都由运行时提供。
- 直接运行文件,输出会带上标签,比如
half-open [1060..1240):、inclusive sum [1060..=1240]:、strictly after 1120:——输出的每一行都能指回产生它的那次调用。
常见问题
运行「用 BTreeMap::range 按边界切片时间桶」会打印什么?
整个文件跑完,输出行以 half-open [1060..1240):、inclusive sum [1060..=1240]:、strictly after 1120: 这类前缀开头。
签名一览:fn main()
核心语句
let total: u32 = buckets.range(1060..=1240).map(|(_, v)| v).sum();
let after_cursor: Vec<_> = buckets.range((Excluded(1120_u64), Included(1240_u64))).collect();
let window: Vec<_> = buckets.range(1060..1240).collect();
代码示例
use std::collections::BTreeMap;
use std::ops::Bound::{Excluded, Included};
fn main() {
let buckets = BTreeMap::from([
(1000_u64, 12_u32),
(1060, 18),
(1120, 9),
(1180, 25),
(1240, 14),
]);
// Half-open [1060, 1240)
let window: Vec<_> = buckets.range(1060..1240).collect();
println!("half-open [1060..1240): {window:?}");
// Inclusive [1060, 1240]
let total: u32 = buckets.range(1060..=1240).map(|(_, v)| v).sum();
println!("inclusive sum [1060..=1240]: {total}");
// Strict cursor resume after key 1120 using explicit Bound
let after_cursor: Vec<_> = buckets.range((Excluded(1120_u64), Included(1240_u64))).collect();
println!("strictly after 1120: {after_cursor:?}");
}