按字段对结构体向量进行分组

Jam*_*mes 2 rust

id我想创建一个包含结构中所有匹配字段的向量,处理该新向量,然后重复该过程。基本上将具有匹配字段的结构分组在一起id

有没有办法不使用不稳定功能来做到这一点drain_filter

#![feature(drain_filter)]

#[derive(Debug)]
struct Person {
    id: u32,
}

fn main() {

    let mut people = vec![];

    for p in 0..10 {
        people.push(Person { id: p });
    }

    while !people.is_empty() {
        let first_person_id = people.first().unwrap().id;

        let drained: Vec<Person> = people.drain_filter(|p| p.id == first_person_id).collect();

        println!("{:#?}", drained);
    }

}
Run Code Online (Sandbox Code Playgroud)

操场

Psi*_*dom 7

id如果您希望按人员 ID 对向量进行分组,那么使用 HashMap from to可能会更有效Vec<Person>,其中每个都id保存一个人员向量。然后你可以循环遍历 HashMap 并处理每个向量/组。这可能比people每次迭代中的排空更有效,在最坏的情况下,时间复杂度为 O(N^2),而 HashMap 的时间复杂度为 O(N)。

#![feature(drain_filter)]
use std::collections::HashMap;

#[derive(Debug)]
struct Person {
    id: u32,
}

fn main() {

    let mut people = vec![];
    let mut groups: HashMap<u32, Vec<Person>> = HashMap::new();

    for p in 0..10 {
        people.push(Person { id: p });
    }

    people.into_iter().for_each(|person| {
        let group = groups.entry(person.id).or_insert(vec![]);
        group.push(person);
    });

    for (_id, group) in groups {
        println!("{:#?}", group);
    }
}
Run Code Online (Sandbox Code Playgroud)

操场