Home > front end >  Sort a vector of structs - Lexicographically (in Rust)
Sort a vector of structs - Lexicographically (in Rust)

Time:02-06

I (a newbie in Rust) am trying to sort a vector of structs lexicographically (first by X-coordinate, and in case of a tie 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)]
    pts.reverse();
    println!("{:?}",pts); // -> [(0.0,2.0), (0.0,0.0), (2.0,2.0), (2.0,0.0)]
    

}

CodePudding user response:

Use a tuple for the comparision:

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

Playground

  •  Tags:  
  • Related