rust 如何将一个HashSet的所有值插入到另一个HashSet中?

hwazgwia  于 2022-12-23  发布在  其他
关注(0)|答案(3)|浏览(174)

我有两个HashSet<u16>,我想实现a = a U b。如果可能的话,我想使用HashSet::union而不是循环或其他调整。
我尝试了以下方法:

use std::collections::HashSet;
let mut a: HashSet<u16> = [1, 2, 3].iter().cloned().collect();
let b: HashSet<u16> = [7, 8, 9].iter().cloned().collect();  

// I can build a union object that contains &u16
let union: HashSet<&u16> = a.union(&b).collect();

// But I can't store the union into a
a = a.union(&b).collect();   //  -> compile error

// of course I can do
for x in &b {
    a.insert(*x);
}
// but I wonder if union could not be used to simply build a union

错误消息如下所示:

the trait bound 
`std::collections::HashSet<u16>: std::iter::FromIterator<&u16>`
is not satisfied

如何执行a = a U b

ego6inou

ego6inou1#

您不需要union-正如您所说,它将创建一个新的HashSet

use std::collections::HashSet;

fn main() {
    let mut a: HashSet<u16> = [1, 2, 3].iter().copied().collect();
    let b: HashSet<u16> = [1, 3, 7, 8, 9].iter().copied().collect();

    a.extend(&b);

    println!("{:?}", a); // {8, 3, 2, 1, 7, 9}
}

Playground
Extend::extend也可以为其他集合实现,例如VecVec的结果会有所不同,因为Vec不像Set那样支持重复项。

h6my8fg2

h6my8fg22#

// But I can't store the union into a
a = a.union(&b).collect();   //  -> compile error

错误消息如下所示:

the trait bound  `std::collections::HashSet<u16>:
std::iter::FromIterator<&u16>` is not satisfied

因为aHashSet<u16>,而a.union(&b)Iterator<Item=&u16>,使用.copied()a.union(&b)转换为Iterator<Item=u16>的工作原理是:

a = a.union(&b).copied().collect(); // compiles

正如前面提到的,这将创建一个新的HashSet,在某些情况下,这可能是你想要的,但如果它被赋给另一个变量,它会更有意义:

let c: HashSet<u16> = a.union(&b).copied().collect();

// a is unchanged here
h43kikqp

h43kikqp3#

要收集多个哈希集:

use std::collections::HashSet;

fn main() {
    let a: HashSet<u16> = [1, 2, 3].iter().copied().collect();
    let b: HashSet<u16> = [1, 3, 7, 8, 9].iter().copied().collect();
    let all = [a,b];
    let combined = all.iter().flatten().collect::<HashSet<_>>();

    println!("{:?}", combined);
}

Playground:https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=44cd73eb3a4e628378cbb7ff11a32649

相关问题