在 Rust 中,如何从 HashMap 的键创建 HashSet? [英] In Rust, how do I create a HashSet from the keys of a HashMap?
本文介绍了在 Rust 中,如何从 HashMap 的键创建 HashSet?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个 HashMap
并且想要计算键的交集.是否可以从 HashMap::keys()
返回的任何内容中构造一个 HashSet
?例如:
I have two HashMap
s and want to compute the intersection of the keys. Is it possible to construct a HashSet
out of whatever HashMap::keys()
returns? For example:
use std::collections::{HashSet, HashMap};
fn main() {
let mut map1: HashMap<i64, i64> = HashMap::new();
let mut map2: HashMap<i64, i64> = HashMap::new();
// Add some values into the HashMaps for demonstration
map1.insert(1, 10);
map1.insert(5, 50);
map2.insert(3, 30);
map2.insert(5, 50);
let set1: HashSet<i64> = HashSet::from(map1.keys()); // How to do this?
let set2: HashSet<i64> = HashSet::from(map2.keys()); // How to do this?
let set3 = set1.intersection(&set2); // What I'm looking to accomplish
// set3 should contain [5], as this is the one key shared by the two HashMaps
}
推荐答案
简单的解决方案
您的代码只需要进行一些调整即可实际编译(参见游乐场):
use std::collections::{HashSet, HashMap};
fn main() {
let mut map1 = HashMap::new();
let mut map2 = HashMap::new();
// Add some values into the HashMaps for demonstration
map1.insert(1, 10);
map1.insert(5, 50);
map2.insert(3, 30);
map2.insert(5, 50);
let set1: HashSet<i64> = map1.keys().cloned().collect();
let set2: HashSet<i64> = map2.keys().cloned().collect();
let set3 = set1.intersection(&set2);
println!("{:?}", set3);
}
特别注意map1.keys().cloned().collect()
:
HashMap
返回一个::keys() Iterator
,.cloned()
将其转换为Iterator
,.collect()
从中构建一个集合,因为HashSet
实现了FromIterator
trait.
HashMap<K, V>::keys()
returns anIterator<Item = &'a K>
,.cloned()
transforms that to anIterator<Item = K>
,.collect()
builds a collection from that, sinceHashSet
implements theFromIterator
trait.
然而,这不是很有效:
- 复杂度明智:
O(map1.size() + map2.size())
. - 内存方面:潜在的大量分配.
直接在HashMap
的键上实现intersection
.
这篇关于在 Rust 中,如何从 HashMap 的键创建 HashSet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文