Movatterモバイル変換


[0]ホーム

URL:


Rust Cookbook

    Sorting Vectors

    Sort a Vector of Integers

    std-badgecat-science-badge

    This example sorts a Vector of integers viavec::sort. Alternative wouldbe to usevec::sort_unstable which can be faster, but does not preservethe order of equal elements.

    fn main() {    let mut vec = vec![1, 5, 10, 2, 15];        vec.sort();    assert_eq!(vec, vec![1, 2, 5, 10, 15]);}

    Sort a Vector of Floats

    std-badgecat-science-badge

    A Vector of f32 or f64 can be sorted withvec::sort_by andPartialOrd::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]);}

    Sort a Vector of Structs

    std-badgecat-science-badge

    Sorts a Vector of Person structs with propertiesname andage by its naturalorder (By name and age). In order to make Person sortable you need four traitsEq,PartialEq,Ord andPartialOrd. These traits can be simply derived.You can also provide a custom comparator function using avec:sort_by method and sort only by age.

    #[derive(Debug, Eq, Ord, PartialEq, PartialOrd)]struct Person {    name: String,    age: u32}impl Person {    pub fn new(name: &str, age: u32) -> Self {        Person {            name: name.to_string(),            age        }    }}fn main() {    let mut people = vec![        Person::new("Zoe", 25),        Person::new("Al", 60),        Person::new("John", 1),    ];    // Sort people by derived natural order (Name and age)    people.sort();    assert_eq!(        people,        vec![            Person::new("Al", 60),            Person::new("John", 1),            Person::new("Zoe", 25),        ]);    // Sort people by age    people.sort_by(|a, b| b.age.cmp(&a.age));    assert_eq!(        people,        vec![            Person::new("Al", 60),            Person::new("Zoe", 25),            Person::new("John", 1),        ]);}

    [8]ページ先頭

    ©2009-2025 Movatter.jp