Sort vector: use sort
and sort_by
method
#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)]
struct Person {
name: &'static str,
age: i32,
}
fn main() {
// sort vector of int
let mut v = vec![3, 1, 4, 2, 5];
v.sort();
println!("V is {:?}", v);
// sort vector of float
// float number implemented PartialOrder trait
let mut v2 = vec![1.3, 3.2, 1.05, 2.3];
v2.sort_by(|a, b| a.partial_cmp(b).unwrap());
println!("V2 is {:?}", v2);
// sort vector of self-defined struct
let mut v3 = vec![
Person {name: "Bob", age: 12},
Person {name: "Alice", age: 18},
Person {name: "Chris", age: 17}
];
v3.sort_by(|a, b| a.age.cmp(&b.age));
println!("V3 is {:?}", v3);
v3.sort_by(|a, b| a.name.cmp(&b.name));
println!("V3 is {:?}", v3);
// we can directly call sort b/c struct
// has derived Eq, Order, PartialEq and PartialOrder
v3.sort();
println!("V3 is {:?}", v3);
}
Result:
V is [1, 2, 3, 4, 5]
V2 is [1.05, 1.3, 2.3, 3.2]
V3 is [Person { name: "Bob", age: 12 }, Person { name: "Chris", age: 17 }, Person { name: "Alice", age: 18 }]
V3 is [Person { name: "Alice", age: 18 }, Person { name: "Bob", age: 12 }, Person { name: "Chris", age: 17 }]
V3 is [Person { name: "Alice", age: 18 }, Person { name: "Bob", age: 12 }, Person { name: "Chris", age: 17 }]
Top comments (0)