正确尝试/捕获无序映射异常
Try/Catch unordered map exception properly
我得到了这个:
// 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");
现在如果我打电话
requestToString.at(GET);
没关系,但是如果我调用不存在的键,例如
requestToString.at(THIS_IS_NO_KNOWN_KEY);
它给出了运行时异常,整个过程中止。
防止这种情况的最佳方法是什么? 是否有编译指示或其他东西,或者我应该"像Java一样"用try/catch块包围它或什么?
好心的亚历克斯
如果找不到
异常,请使用 at
;如果不希望异常终止进程,请在某处处理异常;如果要在本地处理异常,请使用 find
:
auto found = requestToString.find(key);
if (found != requestToString.end()) {
// Found it
do_something_with(found->second);
} else {
// Not there
complain("Key was not found");
}
您可以使用
unordered_map::find
来搜索可能在映射中也可能不在映射中的键。
find
返回一个迭代器,如果未找到键,则为 == end (),如果找到键,则"指向"std::p air。
未编译的代码:
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.
http://www.boost.org/doc/libs/1_38_0/doc/html/boost/unordered_map.html#id3723710-bb 的文档说:
抛出:类型 std::out_of_range
的异常对象(如果不存在此类元素)。
您可以
先使用unordered_map::find
或unordered_map::count
来检查密钥是否存在。
相关文章:
- 递归无序映射
- 正在将无序映射设置为无序映射的值
- 智能指针作为无序映射键,并通过引用进行比较
- 打印无序映射的第二个元素,即集合
- 由并发无序映射查找线程调用的函数是否安全?
- 将大数字(10-12 位数字)存储在无序映射中<字符串,整数>
- 使用无序映射在STL中存储键值对
- 为C++中的无序映射获取给定输入键的错误值
- 将大型对象存储在无序映射中是否效率低下
- 在无序映射的结构化绑定中推导类型
- 使用无序映射进行错误索引
- 将一个向量对放在一个无序映射与一个映射中
- 如何在c++中修改无序映射中的每个值
- C++:使用一对(cpp_int,int)整数作为无序映射中的键(其中cpp_int是boost多精度整数)
- 将 [] 索引到无序映射时出现段错误
- 以std::字符串作为关键字,按字典顺序对一个无序映射进行排序
- 无序映射存储桶的节点大小
- 在无序映射<字符串上使用 find(),向量<string>>与 C++ 中的有序映射花费相同的时间
- 以三个无符号字符为关键字的无序映射
- 无序映射比c++中的映射慢吗