如何在 BTreeSet 中使用自定义比较器函数? [英] How do I use a custom comparator function with BTreeSet?
问题描述
在 C++ 中,可以自定义代码 std::set
用于对其参数进行排序.默认情况下,它使用 std::less
,但可以使用 Compare
模板进行更改参数.
In C++, it is possible to customize the code std::set
uses to sort its arguments. By default it uses std::less
, but that can be changed with the Compare
template parameter.
Rust 的 BTreeSet
使用Ord
trait 对类型.我不知道有什么方法可以覆盖这种行为——它内置在容器存储的类型的类型约束中.
Rust's BTreeSet
uses the Ord
trait to sort the type. I don't know of a way to override this behavior -- it's built into the type constraint of the type stored by the container.
然而,构建一个按一些本地有用的指标排序的项目列表通常是有意义的,但这并不是总是比较项目的最佳方式.或者,假设我想对 use
d 类型的项目进行排序;在这种情况下,即使我想要,也不可能自己为该类型实现 Ord
.
However, it often makes sense to build a list of items that are sorted by some locally-useful metric that nevertheless is not the best way to always compare the items by. Or, suppose I would like to sort items of a use
d type; in this case, it's impossible to implement Ord
myself for the type, even if I want to.
解决方法当然是构建一个普通的旧 Vec
项目,然后 sort
它.但在我看来,这不像在插入时自动排序那么干净.
The workaround is of course to build a plain old Vec
of the items and sort
it afterward. But in my opinion, this is not as clean as automatically ordering them on insertion.
有没有办法在 Rust 的容器类型中使用替代比较器?
Is there a way to use alternative comparators with Rust's container types?
推荐答案
Rust 标准集合中目前不存在自定义比较器.解决问题的惯用方法是定义一个 newtype:
Custom comparators currently do not exist in the Rust standard collections. The idiomatic way to solve the issue is to define a newtype:
struct Wrapper(Wrapped);
然后你可以定义一个自定义的Ord
Wrapper
的实现,具有您想要的语义.
You can then define a custom Ord
implementation for Wrapper
with exactly the semantics you want.
此外,由于您有一个 newtype,您还可以轻松实现其他 trait 以方便转换:
Furthermore, since you have a newtype, you can also easily implement other traits to facilitate conversion:
convert::From
可以实现,给你convert::Into
免费ops::Deref
可以实现,减少由于 auto-deref 导致的映射需求
请注意,访问包装实体在语法上是轻量级的,因为它只有两个字符:.0
.
Note that accessing the wrapped entity is syntactically lightweight as it's just two characters: .0
.
这篇关于如何在 BTreeSet 中使用自定义比较器函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!