i have got this:
// static enum of supported HttpRequest to match requestToString
static const enum HttpRequest {
GET,
POST,
PUT,
DELETE,
OPTIONS,
HEAD,
TRACE
};
// typedef for the HttpRequests Map
typedef boost::unordered_map<enum HttpRequest, const char*> HttpRequests;
// define the HttpRequest Map to get static list of supported requests
static const HttpRequests requestToString = map_list_of
(GET, "GET")
(POST, "POST")
(PUT, "PUT")
(DELETE, "DELETE")
(OPTIONS,"OPTIONS")
(HEAD, "HEAD")
(TRACE, "TRACE");
now if i call
requestToString.at(GET);
it´s ok, but if i call an key which is not present like
requestToString.at(THIS_IS_NO_KNOWN_KEY);
it gives a runtime exception and the whole process aborts..
whats the best way to prevent this? is there a pragma or what ever or should i "java-like" surround it with a try/catch block or what?
kindly alex
Use at if you want an exception if it's not found, and handle the exception somewhere if you don't want it to terminate the process; use find if you want to handle it locally:
auto found = requestToString.find(key);
if (found != requestToString.end()) {
// Found it
do_something_with(found->second);
} else {
// Not there
complain("Key was not found");
}
You can use unordered_map::find to search for a key that may or may not be in the map.
find returns an iterator, which is either == end () if the key is not found, or "points to" a std::pair if the key was found.
Uncompiled code:
unordered_map < int, string > foo;
unordered_map::iterator iter = foo.find ( 3 );
if ( iter == foo.end ())
; // the key was not found in the map
else
; // iter->second holds the string from the map.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With