← 中文资源

简体中文版本

BTreeMap 有序键上的 range 查询

BTreeMap 按键序存储:range 直接给出闭开与闭闭窗口而无需先排序,first/last 以对数复杂度取边界键值,免掉 HashMap 的排序成本。

阅读英文原文

实现说明

BTreeMap 有序键上的 range 查询可以归结为函数 main。 这个示例中仅有的重复出现在 for (name, score) in 里。

使用要点

  • 跑完文件,输出里会留下标记——first:、last:。

常见问题

运行「BTreeMap 有序键上的 range 查询」会打印什么?

整个文件跑完,输出行以 first:、last: 这类前缀开头。

核心语句

.map(|(name, score)| format!("{name}:{score}"))
.collect();

代码示例

use std::collections::BTreeMap;

fn main() {
    // BTreeMap 按键序维护数据:range 查询按序返回,无需先排序
    let mut scores: BTreeMap<String, u32> = BTreeMap::new();
    for (name, score) in
        [("ada", 91), ("lin", 78), ("sam", 88), ("zoe", 95), ("kim", 64)]
    {
        scores.insert(name.to_string(), score);
    }

    // 闭区间窗口:RangeBounds 语法直接表达 kim..=zoe
    let top: Vec<String> = scores
        .range("kim".to_string()..="zoe".to_string())
        .map(|(name, score)| format!("{name}:{score}"))
        .collect();
    println!("{top:?}");

    // 无下界写法:..=lin 从最小键一路取到 lin
    let up_to: Vec<String> = scores
        .range(..="lin".to_string())
        .map(|(name, score)| format!("{name}:{score}"))
        .collect();
    println!("{up_to:?}");

    // 边界访问:first/last 都是对数复杂度
    println!("first: {:?}", scores.first_key_value());
    println!("last: {:?}", scores.last_key_value());
}