Best way to conditionally add to a HashMap, with as few lookups as possible?

房东的猫 提交于 2019-12-21 20:49:32

问题


When using hash maps, it is common to want to add a key:value pair if the key is not already present.

This reads well but isn't as optimal as it could be.

if !map.contains(key) {
    let val = create_val();
    map.insert(key, val);
    some_creation_logic(val);
} else {
    let val = map[key];
    some_update_logic(val);
}

While this works it will always do 2 lookups.

The closest I could get was to use Entry.or_insert (or or_insert_with), counting the length so the else branch can be taken.

let map_len_prev = map.len();
let val = map.or_insert_with(key, create_val);
if map_len_prev != map.len() {
    some_creation_logic(val);
} else {
    some_update_logic(val);
}

Is there a clearer way to insert a value when needed while keeping a way of running both branches of logic for cases it does/doesn't already exist?


回答1:


You can just match the Entry:

use std::collections::hash_map::Entry::{Occupied, Vacant}; 

match map.entry(key) {
    Occupied(val) => {
        some_update_logic(val.get());
    },
    Vacant(entry) => {
        let val = entry.insert(create_val());
        some_creation_logic(val);
    }
}


来源:https://stackoverflow.com/questions/39560296/best-way-to-conditionally-add-to-a-hashmap-with-as-few-lookups-as-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!