pub struct HashMap<K, V>{ /* private fields */ }
Expand description
A hash map implemented with separate chaining collision resolution strategy.
This implementation is focused on hash map functionalities, so we choose to
adopt Rust DefaultHasher
to avoid avalanche of details, and vectors as
the underlying data structure for separate chaining method.
The interface is a simplified version of Rust HashMap
.
References:
Implementations§
Source§impl<K, V> HashMap<K, V>
impl<K, V> HashMap<K, V>
Sourcepub fn new() -> Self
pub fn new() -> Self
Creates an empty map with capacity 0.
The allocation is triggered at the first insertion occurs.
Sourcepub fn with_capacity(cap: usize) -> Self
pub fn with_capacity(cap: usize) -> Self
Creates a map with a given capacity as the number of underlying buckets.
§Parameters
cap
: The number of bucket in the map.
Sourcepub fn get<Q>(&self, key: &Q) -> Option<&V>
pub fn get<Q>(&self, key: &Q) -> Option<&V>
Gets a reference to the value under the specified key.
We use Q here to accept any type that K can be borrowed as. For example,
given a HashMap m using String as key, both m.get(&String) and m.get(&str)
would work because String can be borrow as &str. The same technique is
applied for get_mut
and remove
.
Learn more about Borrow trait:
§Complexity
Constant (amortized).
Sourcepub fn insert(&mut self, key: K, value: V) -> Option<V>
pub fn insert(&mut self, key: K, value: V) -> Option<V>
Inserts key-value pair into the map. Replaces previous value if the same key exists at the same index.
Returns the old value if the key presents. Otherwise returns None
.
Steps are described as following:
- Try to resize hashmap to ensure an appropriate load factor.
- Compute hash of the key to get the inner bucket under certain index.
- Find if there is already a pair with identical key.
- If yes, substitute for it.
- Else, push new value into the bucket.
§Parameters
key
- Key of the pair to insert.value
- Value of the pair to insert.
§Complexity
Constant (amortized).
§Panics
Panics when either hash map cannot make a hash, or cannot access any available bucket to insert new value. These cases shall not happend under a well-implemented resize policy.
Sourcepub fn clear(&mut self)
pub fn clear(&mut self)
Removes all key-value pairs but keeps the allocated memory for reuse.
§Complexity
Linear in the size of the container.
Sourcepub fn bucket_count(&self) -> usize
pub fn bucket_count(&self) -> usize
Sourcepub fn iter(&self) -> impl Iterator<Item = (&K, &V)>
pub fn iter(&self) -> impl Iterator<Item = (&K, &V)>
Creates an iterator that yields immutable reference of each element in arbitrary order.