如何将一个HashSet的所有值插入另一个HashSet? [英] How can I insert all values of one HashSet into another HashSet?
本文介绍了如何将一个HashSet的所有值插入另一个HashSet?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个 HashSet< u16>
s,我想实现 a = a b
.如果可能的话,我想使用 HashSet :: union
而不是循环或其他调整.
I have two HashSet<u16>
s and I would like to implement a = a U b
. If possible, I'd like to use HashSet::union
rather than loops or other tweaks.
我尝试了以下操作:
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 b
?
推荐答案
您不希望 union
—如您所说,它将创建一个新的 HashSet
.相反,您可以使用 Extend :: extend 代码>
:
You don't want union
— as you said, it will create a new HashSet
. Instead you can use Extend::extend
:
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}
}
(游乐场)
Extend :: extend
也是已为其他集合实现,例如 Vec
. Vec
的结果将有所不同,因为 Vec
不会以与 Set
相同的方式兑现重复项.
Extend::extend
is also implemented for other collections, e.g. Vec
. The result for Vec
will differ because Vec
does not honor duplicates in the same way a Set
does.
这篇关于如何将一个HashSet的所有值插入另一个HashSet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文