本文介绍了如何在HashMap中找到值的键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个std::collections::HashMap,其中包含一些条目.我想找到与哈希图中已经存在的特定值相对应的键.

I have a std::collections::HashMap that contains some entries. I want to find the key that corresponds to a particular value that is already in the hash map.

推荐答案

遍历HashMap的条目,找到与值匹配的条目,然后映射到键.

Iterate over the entries of the HashMap, find the entry matching the value, and map to the key.

use std::collections::HashMap;

fn find_key_for_value<'a>(map: &'a HashMap<i32, &'static str>, value: &str) -> Option<&'a i32> {
    map.iter()
        .find_map(|(key, &val)| if val == value { Some(key) } else { None })
}

fn main() {
    let mut map = HashMap::new();
    map.insert(1, "a");
    map.insert(2, "b");
    map.insert(3, "c");

    assert_eq!(find_key_for_value(&map, "a"), Some(&1));
    assert_eq!(find_key_for_value(&map, "z"), None);
}

请注意,这只会找到第一个匹配值,如果要查找 all 个匹配值,则可以使用filter_map并将它们收集到Vec中:

Note that this will only find the first matching value, if you want to find all matching values, you can use filter_map and collect them into a Vec:

use std::collections::HashMap;

fn find_keys_for_value<'a>(map: &'a HashMap<i32, &'static str>, value: &str) -> Vec<&'a i32> {
    map.iter()
        .filter_map(|(key, &val)| if val == value { Some(key) } else { None })
        .collect()
}

fn main() {
    let mut map = HashMap::new();
    map.insert(1, "a");
    map.insert(2, "b");
    map.insert(3, "c");
    map.insert(4, "a");

    let mut keys = find_keys_for_value(&map, "a");
    keys.sort();
    assert_eq!(keys, vec![&1, &4]);
}

这篇关于如何在HashMap中找到值的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:17