问题描述
使用哈希映射时,如果密钥不存在,通常需要添加键:值
对。
$
$ b
如果!map.contains( key){
let val = create_val();
map.insert(key,val);
some_creation_logic(val);
} else {
let val = map [key];
some_update_logic(val);
}
虽然这可以起作用,但它总是会进行2次查找。
最接近我可以使用 Entry.or_insert
(或 or_insert_with
) ,计算长度以便 else
分支。
let map_len_prev = map.len();
let val = map.or_insert_with(key,create_val);
如果map_len_prev!= map.len(){
some_creation_logic(val);
} else {
some_update_logic(val);
$ / code>
是否有更清晰的方式在需要时插入值,同时保留对于它已经/不存在的情况运行两个逻辑分支?
c> Entry : 使用std :: collections :: hash_map :: Entry :: {占用, 空的};
match map.entry(key){
已占用(val)=> {
some_update_logic(val.get());
},
空置(入口)=> {
let val = entry.insert(create_val());
some_creation_logic(val);
}
}
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?
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);
}
}
这篇关于有条件地添加到HashMap的最佳方式,尽可能少的查找?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!