I’m looking for an efficient way to do a conditional insert. Ideally, I’d like a template function that would work on any map. I want something like this:
std::map<int, std::string> MyMap;
if(MyMap.ConditionalInsert(3, "Hello"))
{ // there was no element 3, one has been added with value "Hello"
}
else
{ // there was already an element 3 in the map, it's unchanged
}
I can’t easily use operator[] because there’s no easy way to tell if it created an element or not. I can use count for the test, but then I have to search the map twice if we do an insert. I guess something with find would be best, but it always seems to come out warty and awkward.
Is there a really good way to do this?
What problem do you see with this:
The return value indicates whether the value is already present or not. If it is not present, the value will be inserted, else no value will be inserted.
Taken from here: