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 use
d 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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…