C11: std::Hash Flashcards

1
Q

HashMap<K, V>

A

The type HashMap<K, V> stores a mapping of keys of type K to values of type V using a hashing function, which determines how it places these keys and values into memory

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Creating a new hash map and inserting some keys and values

A

use std::collections::HashMap;

let mut scores = HashMap::new();

scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Accessing Values in a Hash Map

A

use std::collections::HashMap;

let mut scores = HashMap::new();

scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);

let team_name = String::from("Blue");
let score = scores.get(&team_name).copied().unwrap_or(0);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

iterate over each key/value pair in a hash map

A

use std::collections::HashMap;

let mut scores = HashMap::new();

scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);

for (key, value) in &scores {
    println!("{key}: {value}");
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Hash Maps and Ownership

A

For types that implement the Copy trait, like i32, the values are copied into the hash map. For owned values like String, the values will be moved and the hash map will be the owner of those values, as demonstrated in Listing 8-22.

use std::collections::HashMap;

let field_name = String::from("Favorite color");
let field_value = String::from("Blue");

let mut map = HashMap::new();
map.insert(field_name, field_value);
// field_name and field_value are invalid at this point, try using them and
// see what compiler error you get!
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Adding a Key and Value Only If a Key Isn’t Present

A

use std::collections::HashMap;

let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);

scores.entry(String::from("Yellow")).or_insert(50);
scores.entry(String::from("Blue")).or_insert(50);

println!("{:?}", scores);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly