dhardy
dhardy

Reputation: 12164

How can I get the last item in a BTreeMap?

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?

Upvotes: 16

Views: 6001

Answers (3)

rubyu2
rubyu2

Reputation: 270

https://github.com/rust-lang/rust/issues/31690#issuecomment-184445033

A dedicated method would improve discoverability, but you can do:

let map: BTreeMap<K, V> = ...;
let min = map.iter().next();
let max = map.iter().next_back();

and the same for BTreeSet.

Upvotes: 2

Stargateur
Stargateur

Reputation: 26717

The Iterator::rev method requires that Self implements DoubleEndedIterator, so it should always be an optimized and correct choice for your use case.

fn rev(self) -> Rev<Self>
where
    Self: DoubleEndedIterator,

Upvotes: 1

Vladimir Matveev
Vladimir Matveev

Reputation: 127771

btree_map::Iter, which is returned by BTreeMap::iter(), implements DoubleEndedIterator, so indeed, either the approach with rev() would work or you can use the next_back() method directly:

let (key, value) = map.iter().next_back().unwrap();

Upvotes: 24

Related Questions