哪个更好检查密钥是否在C++的hash_map中?at with try ... catch block或find with iterator comparison?

NSF*_*NSF 0 c++ hashmap

据我所知,有两种基本方法可以检查项目是否在hash_map中:

假设我们有一个hash_map: hash_map<string, int> amap

如果我们要检查"abc"是否在地图中,那么我们就可以做到

hash_map<string, int>::iterator itr = amap.find("abc");
if (itr != amap.end()) //in the map
Run Code Online (Sandbox Code Playgroud)

要么:

try {
    int value = amap.at("abc");
}
catch(out_of_range& e) {
    //not there    
}
Run Code Online (Sandbox Code Playgroud)

只是想知道哪一个更好?为了提高效率?

Lil*_*ard 5

使用find().测试迭代器几乎肯定会比捕获异常便宜得多.