How to lookup from and insert into a HashMap efficiently?

前端 未结 1 1551
暗喜
暗喜 2020-11-22 03:15

I\'d like to do the following:

  • Lookup a Vec for a certain key, and store it for later use.
  • If it doesn\'t exist, create an empty Ve
1条回答
  •  心在旅途
    2020-11-22 03:54

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

    use std::collections::hash_map::Entry;
    
    let values: &Vec = 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)
    

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

    map.entry(key).or_insert(default)
    

    0 讨论(0)
提交回复
热议问题