Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Minimum/maximum elements search in BTreeMap/BTreeSet #31690

Closed
abbradar opened this issue Feb 15, 2016 · 7 comments
Closed

Minimum/maximum elements search in BTreeMap/BTreeSet #31690

abbradar opened this issue Feb 15, 2016 · 7 comments
Labels
A-collections Area: std::collections.

Comments

@abbradar
Copy link

It would be nice to have something like (pseudo-code):

fn BTreeMap<K, V>::find{Min,Max}(&self) -> Option<(&K, &V)>;
fn BTreeSet<K, V>::find{Min,Max}(&self) -> Option<&K>;

This should be fast for trees (just walk the tree to the left-most or right-most element) and is very useful. For example Haskell has these functions in its excellent library containers, along with other potentially interesting functions (see the whole "Min/Max" section).

@apasel422
Copy link
Contributor

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.

@abbradar
Copy link
Author

Hm, I haven't known about next_back. What I'm interested however is algorithmic complexity of these -- would this be O(log_2 n) (with all the caveats of using B-tree) or something different?

@apasel422 apasel422 added A-libs A-collections Area: std::collections. labels Feb 15, 2016
@abbradar
Copy link
Author

BTW, I don't see a mention in the documentation that iter() walks items in proper order. It would be nice to add it there, I think.

@abbradar
Copy link
Author

Some thoughts on the matter: if iter() does walk items in order, then we should get min with proper complexity automatically if I understand correctly. So this leaves a question of whether next_back() does the right thing there.

@sfackler
Copy link
Member

It does do the right thing.

@abbradar
Copy link
Author

Thanks! I guess this is purely a documentation issue then. What about changing iter() documentation to something like:

Gets an iterator over the BTreeMap's contents, ordered ascending by its keys. Complexity of first call to next() or next_back() of the resulting iterator is the same as for elements lookup.

(Sorry for possibly bad language, I'm bad at writing documentation)

@apasel422
Copy link
Contributor

Closing this in favor of a new range RFC.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-collections Area: std::collections.
Projects
None yet
Development

No branches or pull requests

3 participants