在锈蚀中,有序集的类型为BTreeSet
。可以使用以下代码行(from documentation)构建这样的集合:
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");
[[0]与有序映射相同。
由于集合是有序的,因此应该有一种方法来获取包含的最大和最小元素。您如何获得它们?
不幸的是,今天的语言没有为此类型提供最大或最小成员方法(或特征)。
在O(log(n))中访问此信息的最佳方法是直接使用迭代器,如开发人员团队在BTreeMap
中提到的那样:
an issue from github
您还可以通过使用迭代器的max()和min()方法来获得集合的最大值和最小值。不幸的是,使用有序集合来执行此操作将浏览整个集合,而忽略了我们从订单中获得的信息。
let map: BTreeSet<V> = ...;
let min = map.iter().next();
let max = map.iter().next_back();
这里// This will be very slow
map.iter().max()
map.iter().min()
显示an issue with a benchmark的两种选择。我在下面复制了基准。
BTreeMap