I came across the following question in stackOverflow std :: map insert or std :: map find?
why is using find () considered inferior to lower_bound () + key_comp ()?
Suppose I have the following map
map<int, int> myMap; myMap[1]=1; myMap[2]=3; myMap[3]=5; int key = xxx;
the suggested answer is to use
map<int, int>::iterator itr = myMap.lower_bound(key); if (itr != myMap.end() && !(myMap.key_comp()(key, itr->first))) { //key found. // do processing for itr->second // }else { //insert into the end position myMap.insert (itr, map<int, int>::value_type(key, value)); }
why is it better than the following?
map<int, int>::iterator itr = myMap.find(key); if (itr != myMap.end()) { //key found. // do processing for itr->second // }else { //insert into the end position myMap.insert (itr, map<int, int>::value_type(key, value)); }
source share