对结构向量进行排序 - 按字典顺序
Sort a vector of structs - Lexicographically
我(Rust 的新手)正在尝试在 Rust 中对结构向量进行排序(首先按 X 坐标,然后按 Y 坐标)。下面的 MWE 沿着 'X' 进行排序,我如何包括沿着 'Y' 的排序?
期望的结果 -> [(0.0,0.0), (0.0,2.0), (2.0,0.0), (2.0,2.0)]
非常感谢您的帮助。谢谢!
#![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.sort_by(|a, b| (a.x, a.y).partial_cmp(&(b.x, b.y)).unwrap());
我(Rust 的新手)正在尝试在 Rust 中对结构向量进行排序(首先按 X 坐标,然后按 Y 坐标)。下面的 MWE 沿着 'X' 进行排序,我如何包括沿着 'Y' 的排序?
期望的结果 -> [(0.0,0.0), (0.0,2.0), (2.0,0.0), (2.0,2.0)]
非常感谢您的帮助。谢谢!
#![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.sort_by(|a, b| (a.x, a.y).partial_cmp(&(b.x, b.y)).unwrap());