I have a std::map of sorts. I want to add an element to this map and replace any existing element that uses its key (if one exists). The thing is, I need to know if the element replaced something, or if it was the first time it was added.
The simple solution is this:
1 2 3 4 5
mymap_t::iterator i = mymap.find( key );
bool replaced = (i != mymap.end());
mymap[key] = value;
The thing is, this is suboptimal because the map has to search for the key twice. Once for find, and again for the [] operator.
How can I accomplish this with only running the key through the map once? I'm thinking there might be some trick with lower_bound and insert, but I can't seem to figure out what lower_bound's deal is.
The first version returns a pair, with its member pair::first set to an iterator pointing to either the newly inserted element or to the element that already had its same value in the map. The pair::second element in the pair is set to true if a new element was inserted or false if an element with the same value existed.
Though lower_bound + the second version of insert should work too.