Search code examples
rustbtreemap

Rust BTreeMap - what is the equivalent of a "peek" or "first" function?


Binary Trees have a root node. Typically with such a data structure implementation, a function is provided to "peek" the root node, as well as the smallest and largest elements.

In other words, in Rust world, I would like to be able to do this:

let map = BTreeMap::new(); // contains T

map.first(); // -> Option<T>
map.last(); // -> Option<T>

I would have expected to find such a function in the documentation, but did not.

What I did find is a function called first_entry and similarly a function called last_entry.

I assume first_entry does something like what I want, but I don't understand how to use it since it returns a type OccupiedEntry. (doc link)

I would assume that first_entry is O(log(N)) and last_entry is O(log(N)), and should there be a similar function for the root, then that would be O(1). (Less important.)


Solution

  • first_entry() and last_entry() are for manipulating the entries. For just accessing them, there are first_key_value() and last_key_value().

    If I understand correctly, both first and last functions are O(log N).