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)));
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)));
The
revord
crate (documentation) provides a struct,RevOrd
, that wraps a value and implementsPartialOrd
andOrd
by callingpartial_cmp
andcmp
with swapped arguments in order to return the reversed order. Just wrap the key to sort in descending order in aRevOrd
struct.Since Rust 1.19, the
std::cmp::Reverse
struct provides the same benefit:You can use
sort_by
paired withOrdering::reverse
instead ofsort_by_key
.This sorts in reverse alphabetical order, then ties are sorted in ascending numerical order:
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.
Here's a similar approach to the problem: create a function for chaining multiple orderings:
Then use
sort_by
, possibly with pattern matching, to produce the ordering of each key:Playground