2

I (a newbie in Rust) am trying to sort a vector of structs (first by X-coordinate, and then by Y-coordinates) in Rust. The MWE below does the sorting along 'X', how do I include the sorting along 'Y' ?

Desired result -> [(0.0,0.0), (0.0,2.0), (2.0,0.0), (2.0,2.0)]

Your help will be be greatly appreciated. Thanks!

#![allow(unused)]

use std::cmp::Ordering;

#[derive(Debug)]
struct Point {
    x: f64,
    y: f64
}

impl PartialOrd for Point {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.x.partial_cmp(&other.x)
    }
}

impl PartialEq for Point {
    fn eq(&self, other: &Self) -> bool {
        self.x == other.x
    }
}

fn main() {
    let p1 = Point { x: 0.0, y: 0.0 };
    let p2 = Point { x: 2.0, y: 0.0 };
    let p3 = Point { x: 2.0, y: 2.0 };
    let p4 = Point { x: 0.0, y: 2.0 };

    let mut pts = vec![];
    pts.push(p1);
    pts.push(p2);
    pts.push(p3);
    pts.push(p4);
    
    pts.sort_by(|a, b| b.x.partial_cmp(&a.x).unwrap());
    println!("{:?}",pts); // -> [(2.0,0.0), (2.0,2.0), (0.0,0.0), (0.0,2.0)]
  
}
Dexter
  • 43
  • 5
  • 1
    Does this answer your question? [How to sort a vector containing structs?](https://stackoverflow.com/questions/69474674/how-to-sort-a-vector-containing-structs) – Herohtar Feb 05 '22 at 23:49

1 Answers1

1

Use a tuple for the comparision:

pts.sort_by(|a, b| (a.x, a.y).partial_cmp(&(b.x, b.y)).unwrap());

Playground

Netwave
  • 40,134
  • 6
  • 50
  • 93