BTreeMap Range Queries Over Sorted Keys

BTreeMap keeps keys ordered so range queries return inclusive and exclusive windows without sorting, with first and last key access at logarithmic cost.

RustData Integrity

Code

rustsnippet
29 lines
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());
}

How the snippet works

BTreeMap Range Queries Over Sorted Keys comes down to the function main.

Repetition is confined to for (name, score) in — the rest of the file is straight-line.

Applying it

The demo output is labeled (first:, last:), so every printed line maps back to its originating operation.

Statements that matter

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

Interactive Tools for This Topic

FAQ

What does BTreeMap Range Queries Over Sorted Keys print when run?
Invoke the file as-is — the `first:`, `last:` prefixes identify which step printed each line.