BTreeMap Split Off Partition
Partition a BTreeMap at a key with split_off, inspect both halves, and confirm the boundary key lands in the right-hand map.
Code
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<_>>());
}How it works
BTreeMap Split Off Partition keeps everything in the function main.
The one repetition in this snippet is the loop for (name, score) in [("ada", 92), ("bob", 75), ("cy", 88), ("dee", 61)].
What to watch for
- The import surface (if any) is all standard library, all versioned with the language itself.
Using it
The primary signature is fn main()
The demo output is labeled (low:, high:, boundary moved:), so every printed line maps back to its originating operation.
Key statements
let high = scores.split_off("cy");
let mut scores = BTreeMap::new();
scores.insert(name, score);
Interactive Tools for This Topic
FAQ
- What does BTreeMap Split Off Partition print when run?
- Running the file directly is enough — expect labeled output lines such as `low:`, `high:`, `boundary moved:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.