简体   繁体   English

如何获得有序集/有序map的最大值和最小值?

[英]How to get the maximum and minimum value of an ordered set / ordered map?

Rust's ordered set is a BTreeSet : Rust 的有序集是一个BTreeSet

 use std::collections::BTreeSet; // Type inference lets us omit an explicit type signature (which // would be `BTreeSet<&str>` in this example). let mut books = BTreeSet::new(); // Add some books. books.insert("A Dance With Dragons"); books.insert("To Kill a Mockingbird"); books.insert("The Odyssey"); books.insert("The Great Gatsby");

An ordered map is a BTreeMap .有序的 map 是BTreeMap

Since the set and map are ordered, there should be a way to get the maximal and minimal element contained.由于集合和 map 是有序的,因此应该有一种方法可以获取包含的最大和最小元素。 How do you get them?你怎么得到它们?

There are no maximum or minimum member methods (inherent or from a trait) for this type.此类型没有最大或最小成员方法(继承或来自 trait)。

The best way to have access to this information in O(log(n)) is to directly use an iterator, as mentioned by the developer team in issue 31690 from GitHub :在 O(log(n)) 中访问此信息的最佳方式是直接使用迭代器,正如开发团队在 GitHub 的issue 31690中提到的那样:

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

You can get the maximum and minimum of a collection by using the Iterator::max() and Iterator::min() methods, but doing this with an ordered set will browse the whole collection, ignoring the information that we have from the order.您可以使用Iterator::max()Iterator::min()方法获取集合的最大值和最小值,但是使用有序集合执行此操作将浏览整个集合,忽略我们从订单中获得的信息.

// This will be very slow
map.iter().max()
map.iter().min()

Issue 59947 has a benchmark showing the two alternatives for BTreeMap :问题 59947 有一个基准,显示BTreeMap的两种替代方案:

 test bench_first... bench: 9 ns/iter (+/- 0) test bench_last... bench: 8 ns/iter (+/- 0) test bench_max... bench: 3,603 ns/iter (+/- 536) test bench_min... bench: 3,755 ns/iter (+/- 328)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM