How do I use a custom comparator function with BTreeSet?

家住魔仙堡 提交于 2021-02-07 11:23:49

问题


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'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.

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 used type; in this case, it's impossible to implement Ord myself for the type, even if I want to.

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.

Is there a way to use alternative comparators with Rust's container types?


回答1:


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

You can then define a custom Ord implementation for Wrapper with exactly the semantics you want.

Furthermore, since you have a newtype, you can also easily implement other traits to facilitate conversion:

  • convert::From can be implemented, giving you convert::Into for free
  • ops::Deref<Target = Wrapped> can be implemented, reducing the need for mapping due to auto-deref

Note that accessing the wrapped entity is syntactically lightweight as it's just two characters: .0.



来源:https://stackoverflow.com/questions/34028324/how-do-i-use-a-custom-comparator-function-with-btreeset

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!