Definition for a string map
As the map is a template typedef is available to use it to map strings.
typedef std::unordered_map<const wxString&,wxString> string_map;
This page will refer to them as string_map. All further code examples expect a map to be declared as:
string_map map;
Add a variable to the map:
There are two options, using the operator[] or using the insert method.
operator[]
map[L"key"]=L"value";
insert()
insert(string_map::value_type(L"key",L"value"));
There are other optional insert methods that specify after which element to do the insertion of the new element.
Read a variable from the map
You might be inclined to use the operator[] again for retrieving values from the map. This works well unless the requested key didn’t actually exist in the map. In that case, a new entry is made in the map with your new key and an empty value (default constructor object). Using the operator[] will also not work when your map is declared const as the operator[] might modify the map, and is therefore not declared as a const method!
The correct method to find a key in the map is to use the find method.
None modifiable map value
string_map::const_iterator it=map.find(L"key");
if(it!=map.end())
{
const wxString& str=it->second;
/* do something with this string... */
} else
{
LOGINFO(L"key not found in map");
}
Note the use of a const_iterator.
Modifiable map values
string_map::iterator it=map.find(L"key");
if(it!=map.end())
{
wxString& str=it->second;
/* do something with this string... */
} else
{
LOGINFO(L"key not found in map");
}
Iterating over all elements in the map
To list all elements in the map use the basic iterator like used with list and vectors.
const string_map::iterator it;
for(it=map.begin();it!=map.end();it++)
{
LOGINFO(L"Key: "<<it.first<<L" value: "<<it.second);
}
As the iterator for a map returns a pair of the key and value these can be accessed using the iterators ‘first’ (for the key) and ‘second’ (for the value) parameters.