Search code examples
c++linuxgccstl

How do I know if std::map insert succeeded or failed?


I have a map in a multithreaded app mapping a class called uuid to pointer. What I want to know if an insert operation succeeded for failed.

e.g.

_mymap.insert(hint, MyMap::value_type(entry.uuid, itemptr));

Does it throw an exception or something if it fails?


Solution

  • In fact the insert method which takes a hint parameter does not return whether the insert succeeded or not. One way to check if insert actually happened would be to check the size of the map before and after insertion. If it is the same, then insert has failed (i.e. the key was already present). I know it sounds ugly, but that's the most efficient way I could come up with. In fact I believe that there is no compelling reason that the insert with a hint should not return a pair (including the bool) just like the regular non-hint insert does. But once it has been specified in an older standard, it is very hard to change, since it is a breaking change, which the C++ community mostly resents.

    Original (wrong) answer

    See this link

    ... 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.

    The link also contains an example

    For example:

    if(mp.insert(make_pair(key, value)).second == false)
    {
       cout << "Insertion failed. Key was present"
    }