首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过与其他HashSet交叉更新原始HashSet,而不是创建新的HashSet

通过与其他HashSet交叉更新原始HashSet,而不是创建新的HashSet
EN

Stack Overflow用户
提问于 2022-06-12 06:59:19
回答 1查看 107关注 0票数 0

Rust的HashSet::intersection函数创建了一个新的HashSet。如何通过两个HashSet交集的结果来更新原始HashSets?

代码语言:javascript
复制
fn main() {
    // intersecting two HashSets, creating a new HashSet: OK
    use std::collections::HashSet;
    let a = HashSet::from(["first", "second", "third"]);
    let b = HashSet::from(["first", "third", "fifth", "ninth"]);
    let intersection: HashSet<_> = a.intersection(&b).collect();
    println!("{:?}", intersection);

    
    // intersecting two HashSets, updating the original HashSet: Failed
    let mut a = HashSet::from(["first", "second", "third"]);
    let b = HashSet::from(["first", "third", "fifth", "ninth"]);
    println!("{:?}", a.intersection(&b).collect::<HashSet<_>>());
    println!("{:?}", a);
    a = a.intersection(&b).collect::<HashSet<_>>();  // doesn't work

    // filter: verbose
    let mut a = HashSet::from(["first", "second", "third"]);
    let b = HashSet::from(["first", "third", "fifth", "ninth"]);
    a = a.iter().filter(|&s| b.contains(s)).map(|s| *s).collect::<HashSet<_>>();
    println!("{:?}", a);
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-06-12 07:04:40

要做到这一点而不分配新的HashSet,您可以使用HashSet::retain,并且只保留第二个HashSet中存在的元素。

代码语言:javascript
复制
fn main() {
    use std::collections::HashSet;
    let mut a = HashSet::from(["first", "second", "third"]);
    let b = HashSet::from(["first", "third", "fifth", "ninth"]);
    println!("{:?}", a.intersection(&b).collect::<HashSet<_>>());
    a.retain(|x| b.contains(x));
    println!("{:?}", a);
}

输出:

代码语言:javascript
复制
{"third", "first"}
{"first", "third"}

游乐场

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72590088

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档