这个实例通过
vec::sort
对一个整数 Vector 进行排序。另一种方法是使用
vec::sort_unstable
,后者运行速度更快一些,但不保持相等元素的顺序。
fn main() {
let mut vec = vec![1, 5, 10, 2, 15];
vec.sort();
assert_eq!(vec, vec![1, 2, 5, 10, 15]);
f32 或 f64 的 vector,可以使用 vec::sort_by
和 PartialOrd::partial_cmp
对其进行排序。
fn main() {
let mut vec = vec![1.1, 1.15, 5.5, 1.123, 2.0];
vec.sort_by(|a, b| a.partial_cmp(b).unwrap());
assert_eq!(vec, vec![1.1, 1.123, 1.15, 2.0, 5.5]);
依据自然顺序(按名称和年龄),对具有 name
和 age
属性的 Person 结构体 Vector 排序。为了使 Person 可排序,你需要四个 traits:Eq
、PartialEq
、Ord
,以及 PartialOrd
。这些 traits 可以被简单地派生。你也可以使用 vec:sort_by
方法自定义比较函数,仅按照年龄排序。
#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)]
struct Person {
name: String,
age: u32
impl Person {
pub fn new(name: String, age: u32) -> Self {
Person {
name,
fn main() {
let mut people = vec![
Person::new("Zoe".to_string(), 25),
Person::new("Al".to_string(), 60),
Person::new("John".to_string(), 1),
// 根据获得的自然顺序(name 和 age)对 people 进行排序
people.sort();
assert_eq!(
people,
vec![
Person::new("Al".to_string(), 60),
Person::new("John".to_string(), 1),
Person::new("Zoe".to_string(), 25),
// 根据 age 值对 people 进行排序
people.sort_by(|a, b| b.age.cmp(&a.age));
assert_eq!(
people,
vec![
Person::new("Al".to_string(), 60),
Person::new("Zoe".to_string(), 25),
Person::new("John".to_string(), 1),