Why std::set does not provide try_emplace member function?

759 Views Asked by At

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

1

There are 1 best solutions below

0
On

std::set::emplace and std::unordered_set::emplace are already equivalent to try_emplace:

Inserts a new element into the container constructed in-place with the given args if there is no element with the key in the container.

However, be aware that:

The element may be constructed even if there already is an element with the key in the container, in which case the newly constructed element will be destroyed immediately.