Sort Vec<Vec<i32>> in ascending order by the first element, and in descending order by the second element when the first element is equal

Viewed 208

For example [[5,6][2,3][2,5][2,9][1,6]] First sort by the first element in ascending order, and when one element is equal, sort by the second element in descending order, resulting in [1,6],[2,9],[2,5],[2,3],[5,6]

1 Answers

You can use sort_by_key() with a key function that returns a tuple of the first subelement followed by its second subelement wrapped in std::cmp::Reverse to reverse its comparison:

v.sort_by_key(|x| (x[0], Reverse(x[1])));

Playground

If you need to sort with a comparison function rather than a key function (e.g. due to the latter's limitations when returning references), a comparator can be nicely expressed using Ordering::then_with():

v.sort_by(|a, b| a[0].cmp(&b[0]).then_with(|| b[1].cmp(&a[1])));
Related