If I understand b-trees correctly, it should be easy and possible in logarithmic time to search for a key. If the key is not existent, it can return the next smaller and larger key; the neighbors of the given key if it would get inserted.
Does this functionality already exist?
One possible but complicated way to do it with the current API is to insert the key and then get an iterator to that key so that we can call next
on this iterator. Although, its also not clear how to get an iterator to a newly inserted element (see this question)
Why are those methods missing or am I missing something?
You can use the range
method and the iterator methods on the returned Range
object:
use std::collections::BTreeMap;
let mut map = BTreeMap::new();
map.insert(2, 0);
map.insert(3, 1);
map.insert(5, 2);
map.insert(7, 3);
map.insert(11, 4);
let key = 6;
// maximum in map less than 6: (5, 2)
println!("maximum in map less than {}: {:?}",
key, map.range(..key).next_back().unwrap());
// minimum in map greater than or equal to 6: (7, 3)
println!("minimum in map greater than or equal to {}: {:?}",
key, map.range(key..).next().unwrap());
next_back()
and next()
both perform tree traversals, so they are reasonably efficient.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With