While looking for an efficient approach to insert to a map only if the key does not exist, I came across this approach:
MapType::iterator lb = mymap.lower_bound(k);
if(lb != mymap.end() && !(mymap.key_comp()(k, lb->first))) {
// key exists. Value accessible from lb->second
} else {
// Do insert. Use lb as a hint to insert so it can avoid another lookup
mymap.insert(lb, MapType::value_type(k, v));
}
That works well for std::map
. However, boost::ptr_map
does not provide a similar form of insert()
i.e. one that accepts an iterator position.
So I'm wondering:
What's the benefit of that approach compared to doing a straight-forward insert? i.e.
std::pair<MapType::iterator, bool> ret; ret = mymap.insert(MapType::value_type(k, v)); if (!ret.second) { // key exists. insertion not done. do something else }
If there's indeed a good reason to use the
lower_bound
approach, is it there an equivalent strategy forboost::ptr_map
? Or would it not be applicable?