哪一个是更好的检查,如果关键是在hash_map在c++ ?At with try..catch块或find with迭

Which one is better to check if the key is in the hash_map in C++? at with try...catch block or find with iterator comparison?

本文关键字:with At c++ catch find 块或 map try hash 检查 更好      更新时间:2023-10-16

据我所知,有两种基本方法可以检查条目是否在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

或:

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

想知道哪个更好吗?出于效率考虑?

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