Object Map
-
template<typename K, typename V>
class ObjectMap - #include <ObjectMap.h>
Implementation of a HashMap for owned objects, i.e. anything created with new().
Example:
Note
Once added to the map the object is destroyed when no longer required.
void test() { ObjectMap<String, MyType> map; MyType* object1 = new MyType(); if (map["key1"] == nullptr) { // Does NOT create entry in map map["key1"] = object1; // Entry now created, "key1" -> object1 } MyType* object2 = new MyType(); map["key1"] = object2; // object1 is destroyed, "key1" -> object2 // Demonstrate use of value reference auto value = map["key1"]; // Returns ObjectMap<String, MyType>::Value object value = new MyType(); // "key1" -> new object value = nullptr; // Free object, "key1" -> nullptr (but still in map) value.remove(); // Free object1 and remove from map // As soon as `map` goes out of scope, all contained objects are destroyed map["key1"] = new MyType(); map["key2"] = new MyType(); }
Public Functions
-
inline ObjectMap()
-
inline ~ObjectMap()
-
inline const V *operator[](const K &key) const
Get value for given key, if it exists.
Note
The caller must not use
delete
on the returned value- Parameters
key –
- Returns
const – V* Will be null if not found in the map
-
inline Value operator[](const K &key)
Access map entry by reference.
- See
Note
If the given key does not exist in the map it will NOT be created
- Parameters
key –
- Returns
Value – Guarded access to mapped value corresponding to given key
-
inline V *find(const K &key) const
Find the value for a given key, if it exists.
Note
If you need to modify the existing map entry, use
operator[]
orvalueAt()
- Parameters
key –
- Returns
V* – Points to the object if it exists, otherwise nullptr
-
inline int indexOf(const K &key) const
Get the index of a key.
- Parameters
key –
- Returns
int – The index of the key, or -1 if key does not exist
-
inline bool contains(const K &key) const
Check if a key is contained within this map.
- Parameters
key – the key to check
- Returns
bool – true if key exists
-
inline void removeAt(unsigned index)
Remove entry at given index.
- Parameters
index – location to remove from this map
-
inline bool remove(const K &key)
Remove a key from this map.
- Parameters
key – The key identifying the entry to remove
- Returns
bool – true if the value was found and removed
-
inline V *extract(const K &key)
Get the value for a given key and remove it from the map, without destroying it.
Note
The returned object must be freed by the caller when no longer required
- Parameters
key –
- Returns
V* –
-
inline V *extractAt(unsigned index)
Get the value at a given index and remove it from the map, without destroying it.
Note
The returned object must be freed by the caller when no longer required
- Parameters
index –
- Returns
V* –
-
inline void clear()
Clear the map of all entries.
-
inline ObjectMap()