BTreeMap::insert, BTreeMap::range, BTreeMap::first_key_value, BTreeMap::last_key_value
pub fn insert(&mut self, key: K, value: V) -> Option<V>
where K: Ord
pub fn range<T, R>(&self, range: R) -> Range<'_, K, V>
where T: Ord + ?Sized, K: Borrow<T> + Ord, R: RangeBounds<T>
pub fn first_key_value(&self) -> Option<(&K, &V)>
where K: Ord
pub fn last_key_value(&self) -> Option<(&K, &V)>
where K: OrdInsert into an ordered map, walk a key range, and read the first and last entries. Iteration is in key order.
| Parameter | Description |
|---|---|
key / value | insert takes ownership of the key and value. The key type must implement Ord. |
range | A range bound such as "b".."d", "b".., or ..= "c". Keys are borrowed for the comparison. |
Returns: insert returns Option<V> with the previous value. range returns an iterator of (&K, &V). first_key_value and last_key_value return Option<(&K, &V)>.
- Keys were inserted as c, a, b, d and printed in key order as a, b, c, d. That order is part of the BTreeMap contract, unlike HashMap.
- The HashMap page still holds the original compare-in-key-order recipe. See the related links.
use std::collections::BTreeMap;
fn main() {
let mut map = BTreeMap::new();
map.insert("c", 3);
map.insert("a", 1);
map.insert("b", 2);
map.insert("d", 4);
print!("btree-iter");
for (k, v) in &map {
print!(" {k}={v}");
}
println!();
print!("range");
for (k, v) in map.range("b".."d") {
print!(" {k}={v}");
}
println!();
println!("first {:?} last {:?}", map.first_key_value(), map.last_key_value());
}Expected output
btree-iter a=1 b=2 c=3 d=4
range b=2 c=3
first Some(("a", 1)) last Some(("d", 4))Related: HashMap page, Original ordered-maps recipe