Added core::cmp::Reverse for sort_by_key reverse sorting
This commit is contained in:
parent
134c4a0f08
commit
d7d4e670ed
1 changed files with 34 additions and 0 deletions
|
|
@ -322,6 +322,40 @@ impl Ordering {
|
|||
}
|
||||
}
|
||||
|
||||
/// A helper struct for reverse ordering.
|
||||
///
|
||||
/// This struct is a helper to be used with functions like `Vec::sort_by_key` and
|
||||
/// can be used to reverse order a part of a key.
|
||||
///
|
||||
/// Example usage:
|
||||
///
|
||||
/// ```
|
||||
/// use std::cmp::Reverse;
|
||||
///
|
||||
/// let mut v = vec![1, 2, 3, 4, 5, 6];
|
||||
/// v.sort_by_key(|&num| (num >= 3, Reverse(num)));
|
||||
/// assert_eq!(v, vec![3, 2, 1, 6, 5, 4]);
|
||||
/// ```
|
||||
#[derive(PartialEq, Eq, Debug)]
|
||||
#[stable(feature = "rust1", since = "1.8.0")]
|
||||
pub struct Reverse<T: Ord + PartialOrd + Eq + PartialEq>(pub T);
|
||||
|
||||
#[stable(feature = "rust1", since = "1.8.0")]
|
||||
impl<T: Ord + PartialOrd + Eq + PartialEq> PartialOrd for Reverse<T> {
|
||||
#[inline]
|
||||
fn partial_cmp(&self, other: &Reverse<T>) -> Option<Ordering> {
|
||||
other.0.partial_cmp(&self.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[stable(feature = "rust1", since = "1.8.0")]
|
||||
impl<T: Ord + PartialOrd + Eq + PartialEq> Ord for Reverse<T> {
|
||||
#[inline]
|
||||
fn cmp(&self, other: &Reverse<T>) -> Ordering {
|
||||
other.0.cmp(&self.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order).
|
||||
///
|
||||
/// An order is a total order if it is (for all `a`, `b` and `c`):
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue