One advantage of try_emplace
member function of std::map
(and std::unordered_map
) is that it does not allocate a new node if the key already exists in the map. I wonder why this member function has not been added to the std::set
(and std::unordered_set
) interface, where the same advantage might apply as well.
This live demo shows that std::set::emplace
allocates each time: https://godbolt.org/z/MjMjPcc89 (with libstdc++).
And this benchmark shows that find
+ emplace
may be faster than emplace
alone when there are duplicated keys: https://quick-bench.com/q/2IWzv_SJFJpklGjwIKk6wgKsuz0.
However, find
+ emplace
requires a double lookup in case the key is not present in the container. Here is the benchmark for std::map
, where try_emplace
is the fastest option: https://quick-bench.com/q/ymn1qaxAtrf6FTzHC98e_wkHVZ4.
EDIT
It seems the problem with allocations does not occur when std::set::insert
is used. My bad I haven't tried it before.
Live demo: https://godbolt.org/z/EjWjfjnsc
std::set::emplace and std::unordered_set::emplace are already equivalent to
try_emplace
:However, be aware that: