Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ equivalent to Java Map getOrDefault?

Tags:

c++

c++17

treemap

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/

like image 803
Evan Avatar asked Apr 28 '26 03:04

Evan


1 Answers

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.

like image 196
L. F. Avatar answered Apr 29 '26 17:04

L. F.