简体   繁体   中英

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?

As far as I know there are two basics ways to check if an item is in the hash_map:

Let's say we have a hash_map: hash_map<string, int> amap

If we are gonna check whether "abc" is in the map then we can do

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

or:

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

Just wanna know which one is better? for efficiency concern?

Use find() . Testing the iterator is almost certainly going to be much cheaper than catching an exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM