SHARE
TWEET

Untitled

a guest Jan 20th, 2019 50 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use std::cmp::{Ordering};
  2.  
  3. #[derive(PartialEq, Eq, Debug)]
  4. struct Thing {
  5.     name: String,
  6.     score: u8,
  7. }
  8.  
  9. impl PartialOrd for Thing {
  10.     fn partial_cmp(&self, other: &Thing) -> Option<Ordering> {
  11.         match self.score.cmp(&other.score) {
  12.             Ordering::Greater => Some(Ordering::Less),
  13.             Ordering::Less => Some(Ordering::Greater),
  14.             Ordering::Equal => Some(self.name.cmp(&other.name)),
  15.         }
  16.     }
  17. }
  18.  
  19. impl Ord for Thing {
  20.     fn cmp(&self, other: &Thing) -> Ordering {
  21.         match self.score.cmp(&other.score) {
  22.             Ordering::Greater => Ordering::Less,
  23.             Ordering::Less => Ordering::Greater,
  24.             Ordering::Equal => self.name.cmp(&other.name),
  25.         }
  26.     }
  27. }
  28.  
  29.  
  30. impl Thing {
  31.     fn new(name: String, score: u8) -> Self {
  32.         Thing { name, score }
  33.     }
  34. }
  35.  
  36. fn main() {
  37.     let names = vec!["e", "d", "c", "b", "a"];
  38.     let scores = vec![4, 5, 5, 3, 7];
  39.  
  40.     let mut things = names
  41.         .into_iter()
  42.         .zip(scores.into_iter())
  43.         .map(|(n, s)| Thing::new(n.to_owned(), s))
  44.         .collect::<Vec<_>>();
  45.  
  46.     things.sort();
  47.     for thing in things {
  48.         println!("{:?}", thing);
  49.     }
  50. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top