If you have a sorted map of key/value pairs (or just keys), one of the obvious operations is to get the first or last pair (or key).
C++'s std::vector
has front()
and back()
for this purpose. std::map
doesn't, but *map.begin()
and *map.rbegin()
(reverse iterator) work for this (assuming one knows the map is not empty).
In Rust, getting the first element of a map seems to require map.iter().next().unwrap()
— ugly, but perhaps justified considering some error checking is needed.
How can we get the last element? By stepping over all elements: map.iter().last().unwrap()
?
I see that there is Iterator::rev()
, so is map.iter().rev().next().unwrap()
a reasonable alternative?
https://github.com/rust-lang/rust/issues/31690#issuecomment-184445033
A dedicated method would improve discoverability, but you can do:
The
Iterator::rev
method requires thatSelf
implementsDoubleEndedIterator
, so it should always be an optimized and correct choice for your use case.btree_map::Iter
, which is returned byBTreeMap::iter()
, implementsDoubleEndedIterator
, so indeed, either the approach withrev()
would work or you can use thenext_back()
method directly: