C++ Maps 👷🏼♂️👷🏼♀️
Creating Maps
Declaring
#include <map>
std::map<int,std::string> my_map;
Populating
TODO Need to write up my notes about this
Accessing Items using a Key
action | outcome |
---|---|
[key] |
inserts key if it isn't found in map |
find(key) |
returns iterator to the map. if the key not found, the iterator points at map.end() |
at(key) |
throws an exception if the key is not found. |
iterator.second()
points at the value in the [key,value] pair.
Looping through a map
Using an iterator
Using
mymap.begin()
to get an iterator (the type for this is a candidate for theauto
keyword!)- the iterator can be incremented with
++
- compare the iterator with
mymap.end()
to check for the end (mymap.end()
points to the space AFTER the last item)
std::map<std::string, int>::iterator it = my_map.begin();
while (it != my_map.end()) {
std::string key = it->first;
int value = it->second;
it++;
}
And naturally this can be done in a for loop at well.
for(auto it= my_map.begin(); it!=my_map.end(); it++) {
// DO STUFF
}
Using a ranged for loop (C++11)
for (std::pair<std::string, int> element : my_map) {
std::string key = element.first;
int value = element.second;
}
Destroying Maps
The elements in a map can be removed with map.clear()
And of course, if the map was created with new
, it needs a delete
A note about pointers
If a map contains pointers, will need to delete the memory allocated to those pointers (if appropriate to do so - i.e. if the map owns that data - in other words if the structure pointed to was created as it was inserted into the map). This can be done by iterating through the map. HOWEVER by using smart pointers freeing allocated memory is handled by the pointer system itself - so no need for your code to free the memory up