实现说明
BTreeMap Split Off 分区的核心是函数 main。
for (name, score) in [("ada", 92), ("bob", 75), ("cy", 88), ("dee", 61)] 承担全部的逐项处理。
使用要点
- 演示输出是带标签的(
low:、high:、boundary moved:),每个操作都会留下自己的一行标注。
常见问题
运行「BTreeMap Split Off 分区」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 low:、high:、boundary moved: 这类标签。
核心语句
let high = scores.split_off("cy");
let mut scores = BTreeMap::new();
scores.insert(name, score);
代码示例
use std::collections::BTreeMap;
fn main() {
let mut scores = BTreeMap::new();
for (name, score) in [("ada", 92), ("bob", 75), ("cy", 88), ("dee", 61)] {
scores.insert(name, score);
}
// split_off keeps keys below the bound and returns the rest
let high = scores.split_off("cy");
println!("low: {scores:?}");
println!("high: {high:?}");
// the boundary key belongs to the right-hand map
println!("boundary moved: {}", high.contains_key("cy"));
// the two halves no longer share structure
let mut low = scores;
low.insert("eve", 70);
println!("low keys: {:?}", low.keys().collect::<Vec<_>>());
println!("high keys: {:?}", high.keys().collect::<Vec<_>>());
}