简体   繁体   中英

How do I remove the elements of vector that occur in another vector in Rust?

I want the disjoint result. This is the best I can come up with:

for rem in &remove_vec {
    orig_vec.retain(|i| !i.eq(rem));
}

You are using the wrong tool for the job. Instead, convert the items to remove into a set, either BTreeSet or HashSet :

use std::{collections::BTreeSet, iter::FromIterator};

fn demo<T>(mut items: Vec<T>, to_remove: Vec<T>) -> Vec<T>
where
    T: std::cmp::Ord,
{
    let to_remove = BTreeSet::from_iter(to_remove);

    items.retain(|e| !to_remove.contains(e));

    items
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM