How can I get the last item in a BTreeMap?

本小妞迷上赌 提交于 2019-12-01 20:08:41

问题


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?


回答1:


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();



回答2:


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,



回答3:


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.


来源:https://stackoverflow.com/questions/33699076/how-can-i-get-the-last-item-in-a-btreemap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!