dessalines
dessalines

Reputation: 7372

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));
}

Upvotes: 0

Views: 1356

Answers (1)

Shepmaster
Shepmaster

Reputation: 430663

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
}

Upvotes: 5

Related Questions