我有两个HashMap,想要计算关键点的交点.有没有可能在HashMap::keys()个返回值中构造一个HashSet?例如:

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
}

推荐答案

简单的解决方案

你的代码只需要一些调整就可以真正编译(see Playground):

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<K, V>::keys()返回Iterator<Item = &'a K>
  • .cloned()将其转换为Iterator<Item = K>
  • .collect()从中构建一个集合,因为HashSet实现了FromIterator特征.

然而,这并不是很有效:

  • 复杂性方面:O(map1.size() + map2.size()).
  • 内存方面:潜在的大分配.

有效的解决方案

直接在HashMap键上执行intersection.

Rust相关问答推荐

基于对vec值的引用从该值中删除该值

泛型属性比较

关联类型(类型参数)命名约定

通过解引用将值移出Box(以及它被脱糖到什么地方)?

如何在 struct 的自定义序列化程序中使用serde序列化_WITH

为什么这是&q;,而让&q;循环是无限循环?

变量需要parse()中的显式类型

try 创建随机数以常量

应为关联类型,找到类型参数

如何实现Deref;多次;?

实现 Deref 的 struct 可以返回对外部数据的引用吗?

为什么在 Allocator API 中 allocate() 使用 `[u8]` 而 deallocate 使用 `u8` ?

Rust编译器通过哪些规则来确保锁被释放?

在 Rust 中,Weak 如何知道内部值何时被删除?

无法理解 Rust 对临时值的不可变和可变引用是如何被删除的

为什么 i32 Box 类型可以在 Rust 中向下转换?

在 Rust 中返回对枚举变体的引用是个好主意吗?

使用泛型作为关联类型,没有幻像数据

在使用大型表达式时(8k 行需要一小时编译),是否可以避免 Rust 中的二次编译时间?

如何在没有 `make_contiguous()` 的情况下对 VecDeque 进行排序或反转?