如何获得有序集合/有序映射的最大值和最小值?

问题描述 投票:2回答:1

Rust的有序集是BTreeSet

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

由于set和map是有序的,因此应该有一种方法来获取包含的最大和最小元素。您如何获得它们?

rust b-tree ordered-map ordered-set
1个回答
3
投票

此类型没有最大或最小成员方法(固有的或来自特征的。)>

[O(log(n))中访问此信息的最佳方法是直接使用迭代器,如开发人员团队在BTreeMap中提到的那样:

BTreeMap

您可以使用issue 31690 from GitHublet map: BTreeSet<V> = ...; let min = map.iter().next(); let max = map.iter().next_back(); 方法来获得集合的最大值和最小值,但是使用有序集合进行操作将浏览整个集合,而忽略了我们从订单中获得的信息。

Iterator::max()

[Iterator::min()显示// This will be very slow map.iter().max() map.iter().min() 的两个选择:

Issue 59947 has a benchmark
© www.soinside.com 2019 - 2024. All rights reserved.