Game Development Reference
In-Depth Information
Values in an
unordered_map
are accessed a little differently. You will have to use either the
[]
operator
or the
at
method. Both are shown in Listing 16-11.
Listing 16-11. Using
[]
and
at
string& myString = myUnorderedMap[2];
cout << "Found : " << myString << endl;
myString = myUnorderedMap.at(2);
cout << "Found : "<< myString << endl;
These methods differ in a very significant way. The
[]
operator can be used to insert or retrieve
values from an
unordered_map
. If the key 2 had not existed in
myUnorderedMap
, a new
string
would
have been added to the map and its reference returned. If the key did already exist, the current string
would have been returned. The
at
method never adds a new element to our
unordered_map
, instead
it throws an exception. Listing 16-12 shows how you can update the
at
call to handle exceptions.
Listing 16-12. Handling Exceptions
try
{
string& myString = myUnorderedMap.at(5);
cout << "Found : " << myString << endl;
}
catch (const std::out_of_range& outOfRange)
{
cout << "Out of range error: " << outOfRange.what() << endl;
}
Your program would have crashed with an unhandled exception error if you had called this code
without the
try...catch
block. Throwing your own exceptions is as easy as using the
throw
keyword, as you can see in Listing 16-13.
Listing 16-13. Throwing Exceptions
void ExceptionExample()
{
if (true)
{
throw -1;
}
}
Catching an exception from this method is shown in Listing 16-14.