Template Class HashMap
Defined in File hash_map.hpp
-
template<typename Key, typename Value>
class HashMap A hash map implementation using open addressing with linear probing.
This class provides a fixed-capacity hash map that uses pre-allocated memory and linear probing for collision resolution. It supports basic operations like insert, get, erase, and has. The hash map is designed for performance-critical scenarios where memory allocation should be minimized.
- Template Parameters
Key – The key type for the hash map.
Value – The value type for the hash map.
Public Types
-
enum class Error
Error codes used by this class.
Values:
-
enumerator kInvalidArgument
kInvalidArgument is returned when a function is called with argument that does not make sense such as negative size or capacity smaller than size.
-
enumerator kOutOfMemory
kOutOfMemory is returned when a memory allocation fails.
-
enumerator kHashMapFull
kHashMapFull is returned if the hash map is full.
-
enumerator kKeyNotFound
kKeyNotFound is returned if the key is not found in the hash map.
-
enumerator kKeyAlreadyExists
kKeyAlreadyExists is returned if the key already exists in the hash map.
-
enumerator kInvalidArgument
-
using unexpected_t = unexpected<Error>
Unexpected type used by this class.
-
using hash_t = uint64_t
Hash type used internally.
Public Functions
-
HashMap() = default
Default constructor used to be able to pre-allocate memory.
-
inline expected_t<void> reserve(int32_t size, int32_t capacity)
Reserve memory for the hash map.
- Parameters
size – Maximum number of elements the hash map can store.
capacity – Total capacity of the internal array (should be larger than size for efficiency).
- Returns
Success or error status.
-
inline bool has(const Key &key) const
Check if a key exists in the hash map.
- Parameters
key – The key to search for.
- Returns
True if the key exists, false otherwise.
-
inline expected_t<Value> get(const Key &key) const
Get the value associated with a key.
- Parameters
key – The key to search for.
- Returns
Value associated with the key on success, Error::kKeyNotFound if key doesn’t exist.
-
inline expected_t<void> insert(const Key &key, Value value)
Insert a key-value pair into the hash map.
- Parameters
key – The key to insert.
value – The value to associate with the key.
- Returns
Success or error status. Error::kHashMapFull if the map is full, Error::kKeyAlreadyExists if the key already exists.
-
inline expected_t<void> erase(const Key &key)
Remove a key-value pair from the hash map.
- Parameters
key – The key to remove.
- Returns
Success or error status. Error::kKeyNotFound if the key doesn’t exist.
-
inline int32_t size() const
Get the current number of elements in the hash map.
- Returns
Current size of the hash map.