std:1.29.1 https://doc.rust-lang.org/std
这个实例通过 [vec::sort
]https://doc.rust-lang.org/std/vec/struct.Vec.html#method.sort对一个整数 Vector 进行排序。另一种方法是使用 [vec::sort_unstable
]https://doc.rust-lang.org/std/vec/struct.Vec.html#method.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
]https://doc.rust-lang.org/std/primitive.slice.html#method.sort_by和 [PartialOrd::partial_cmp
]https://doc.rust-lang.org/std/cmp/trait.PartialOrd.html#tymethod.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:方法自定义比较函数,仅按照年龄排序。
#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)]
struct Person {
name: String,
age: u32
}
impl Person {
pub fn new(name: String, age: u32) -> Self {
Person {
name,
age
}
}
}
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),
]);
}
以上实例代码都是完整的、可独立运行的程序,因此你可以直接复制它们到自己的项目中进行试验。如果希望从头了解如何运行上述实例代码,请参考《Rust 实践指南》中关于本书-如何使用本书实例部分。也可以复制链接: