用多个键排序时反转特定键 [英] Reverse specific key when sorting with multiple keys
问题描述
使用多个键排序时,如何颠倒单个键的顺序?例如:
When sorting with multiple keys, how can I reverse the order of an individual key? For example:
vec.sort_by_key(|k| (foo(k).reverse(), bar(k)));
推荐答案
您可以使用 这将按相反的字母顺序进行排序,然后按数字升序对关系进行排序: This sorts in reverse alphabetical order, then ties are sorted in ascending numerical order: 由于Rust 1.17(通过 RFC 1677 ),您可以编写它像这样: Since Rust 1.17 (via RFC 1677), you can write it like this: 如果您可以自然地将其取反/取反,则可以简单地取消密钥. If you have something that can naturally be negated / inverted, you can simply negate the key. 这篇关于用多个键排序时反转特定键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!sort_by
与
[Foo("beta", 1), Foo("beta", 2), Foo("alpha", 1)]
vec.sort_by(|a, b| {
a.name().cmp(b.name()).reverse()
.then(a.len().cmp(&b.len()))
});