Why set/map emplace_hint does not return a boolean

The easiest way to determine, whether the emplace took place or not, is to store the size() of the map in a variable and test, whether that size has increased after the emplace_hint():

auto oldsz = myMap.size();
myMap.emplace_hint(it, args...);
if(myMap.size() > oldsz) {
    // emplace was accepted
} else {
    // the emplace was rejected, as it would have overwritten an element
}

The same code can also be used with insert_or_assign(), if the new value shall overwrite the old in case of an already existing key.


emplace_hint does that likely for consistency with the hinted insert: emplace was initially proposed as a pair of overloads, mirroring insert, but the hinted overload was renamed after LWG 763, although Josuttis wanted to rename the non-hinted version instead)

The hinted insert for associative containers takes an iterator and a value and returns an iterator in order to be compatible with the regular insert on sequential containers in generic code. as mentioned in Josuttis's book. This compatibility is exploited by std::inserter

Tags:

C++

Stl

C++11