[英]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?
据我所知,有两种检查项目是否在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()
。 测试迭代器几乎肯定比捕获异常便宜得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.