如何有效地从 HashMap 中查找和插入? [英] How to lookup from and insert into a HashMap efficiently?

查看:18
本文介绍了如何有效地从 HashMap 中查找和插入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想执行以下操作:

  • 为某个键查找Vec,并将其存储以备后用.
  • 如果它不存在,则为该键创建一个空的 Vec,但仍将其保留在变量中.
  • Lookup a Vec for a certain key, and store it for later use.
  • If it doesn't exist, create an empty Vec for the key, but still keep it in the variable.

如何有效地做到这一点?自然地,我认为我可以使用 match:

How to do this efficiently? Naturally I thought I could use match:

use std::collections::HashMap;

// This code doesn't compile.
let mut map = HashMap::new();
let key = "foo";
let values: &Vec<isize> = match map.get(key) {
    Some(v) => v,
    None => {
        let default: Vec<isize> = Vec::new();
        map.insert(key, default);
        &default
    }
};

当我尝试它时,它给了我如下错误:

When I tried it, it gave me errors like:

error[E0502]: cannot borrow `map` as mutable because it is also borrowed as immutable
  --> src/main.rs:11:13
   |
7  |     let values: &Vec<isize> = match map.get(key) {
   |                                     --- immutable borrow occurs here
...
11 |             map.insert(key, default);
   |             ^^^ mutable borrow occurs here
...
15 | }
   | - immutable borrow ends here

我最终做了这样的事情,但我不喜欢它执行两次查找的事实(map.contains_keymap.get):

I ended up with doing something like this, but I don't like the fact that it performs the lookup twice (map.contains_key and map.get):

// This code does compile.
let mut map = HashMap::new();
let key = "foo";
if !map.contains_key(key) {
    let default: Vec<isize> = Vec::new();
    map.insert(key, default);
}
let values: &Vec<isize> = match map.get(key) {
    Some(v) => v,
    None => {
        panic!("impossiburu!");
    }
};

有没有一种安全的方法可以只用一个 match 来做到这一点?

Is there a safe way to do this with just one match?

推荐答案

entry API 就是为此而设计的.在手动形式中,它可能看起来像

The entry API is designed for this. In manual form, it might look like

use std::collections::hash_map::Entry;

let values: &Vec<isize> = match map.entry(key) {
    Entry::Occupied(o) => o.into_mut(),
    Entry::Vacant(v) => v.insert(default)
};

或者可以使用更简洁的形式:

Or one can use the briefer form:

map.entry(key).or_insert_with(|| default)

如果 default 即使没有插入也可以计算/便宜,它也可以是:

If default is OK/cheap to compute even when it isn't inserted, it can also just be:

map.entry(key).or_insert(default)

这篇关于如何有效地从 HashMap 中查找和插入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆