Search code examples
c++c++17treemap

C++ equivalent to Java Map getOrDefault?


Java's getOrDefault was a nice construct for one line access to a map value or the starting point if one does not exist. I do not see anything in the map reference in C++ with a parallel. Does something exist or is it build your own?

I have objects in the map that I would update if they exist, but construct new if they do not. With getOrDefault, I could construct the object on the default side, or access it if it exists.

http://www.cplusplus.com/reference/map/map/

https://www.geeksforgeeks.org/hashmap-getordefaultkey-defaultvalue-method-in-java-with-examples/


Solution

  • I have objects in the map that I would update if they exist, but construct new if they do not. With getOrDefault, I could construct the object on the default side, or access it if it exists.

    Use emplace.

    auto& element = *map.emplace(key, value).first;
    

    emplace inserts a new element if the key is not present, and returns a pair consisting of an iterator to the element (inserted or already existent) and a bool value indicating whether insertion took place.