Updating HashMap values

Hi, I need some advice. Until now i have been updating my hash tables using this the following strategy

use fxhash::FxHashMap;

fn main(){
    let mut map = FxHashMap::default();

    // add entries 
    map.entry("A".to_string()).or_insert_with(FxHashMap::default).insert(vec![5u8,9,7], (0,3));
    map.entry("A".to_string()).or_insert_with(FxHashMap::default).insert(vec![9u8,9,7], (0,3));

    let key = vec![9u8,9,7];

    // update an entry value
    if map["A"].contains_key(&key) {
        let x = map["A"][&key].0;
        map.entry("A".to_string()).or_insert_with(FxHashMap::default).insert(key, (x+1,3));
    }
   println!("{:#?}", map);
 }

Now i am a bit worried if i am not affecting the speed the algorithm in case i do the update call within a loop. Also updating a value by (re)inserting a new hashmap does not seam as the right way to do this. so my question is, given the hashmap structure as defined above what would be the most elegant way to update the value within a tuple?

thnx
A

Instead of reinserting, you can use get_mut() to get a mutable reference to a value if it already exists.

use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();

    let mut inner = HashMap::new();
    inner.insert(vec![5u8, 9, 7], (0, 3));

    map.insert("a".to_string(), inner);
    println!("{:?}", map);

    // Use get_mut() to get a mutable reference to the value, then pattern match
    // to get a &mut reference to the "0".
    let (ref mut x, _) = map
        .get_mut("a")
        .and_then(|inner| inner.get_mut([5_u8, 9, 7].as_ref()))
        .expect("We just inserted it");
    *x += 1;

    println!("{:?}", map);
}

(playground)

Generates the following output:

{"a": {[5, 9, 7]: (0, 3)}}
{"a": {[5, 9, 7]: (1, 3)}}
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.