Rust中使用flatten迭代HashMap组成的Vec并统计指定值数量的惯用方法
问题描述
基础定义
你已经定义了第一个HashMap:
let mut map = HashMap::new(); map.insert(String::from("one"), 1); map.insert(String::from("two"), 2); map.insert(String::from("three"), 3);
已实现的单HashMap统计逻辑
你已经完成了单个HashMap中指定值出现次数的统计方法:
fn count_map(hm: &HashMap<String, i32>, v: i32) -> usize { hm.iter().filter(|&(_, b)| *b == v).count() } count_map(&map, 2)
新增场景
你新增了第二个HashMap,并且把两个HashMap存入了Vec中:
let mut map = HashMap::new(); map.insert(String::from("one"), 1); map.insert(String::from("two"), 2); map.insert(String::from("three"), 3); let mut map2 = HashMap::new(); map2.insert(String::from("two"), 2); map2.insert(String::from("four"), 4); map2.insert(String::from("six"), 6); let vec_map = vec![map, map2];
需求
需要用flatten方法遍历vec_map统计指定值的总出现次数,完成以下函数的实现:
fn count_hm_two(vec_map: &[HashMap<String, i32>], v: i32) -> usize { vec_map.iter()??? }
实现方案
flatten的作用是把双层迭代器拍平为单层迭代器:这里vec_map.iter()会先迭代Vec中的每个HashMap引用,再通过flatten自动遍历每个HashMap内部的键值对,直接得到所有键值对的单层迭代器,后续筛选统计逻辑和单HashMap场景一致。
完整实现代码如下:
fn count_hm_two(vec_map: &[HashMap<String, i32>], v: i32) -> usize { vec_map .iter() // 生成Vec中所有HashMap的引用迭代器 .flatten() // 拍平迭代器,直接输出所有HashMap中的(&String, &i32)键值对 .filter(|&(_, val)| *val == v) // 筛选值等于目标v的条目 .count() // 统计符合条件的条目总数 }
内容的提问来源于stack exchange,提问作者marrowgari
相关产品推荐
相关产品推荐

