std::unorde...set::emplace(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’– std::unordered_set::emplace(3) πŸ’–

Okay bestie, this page is labeled std::unorde...set::emplace(3) in the C++ Standard Libary manual, and it’s all about std::unordered_set::emplace. The vibe? Constructing elements in place and dodging unnecessary copies or moves if you use it carefully. πŸ’…

πŸ’– NAME πŸ’–

std::unordered_set::emplace β€” literally std::unordered_set::emplace, bestie. Same name, same function, iconic behavior. 😌

✨ Synopsis ✨

Here’s the signature, no cap:

template< class... Args >                             (since C++11)
std::pair<iterator, bool> emplace( Args&&... args );

Okay so what it does: inserts a new element into the container, constructed in-place with the args you gave it, but only if there’s no element with the key already in the container. Periodt.

The constructor of the new element gets called with exactly the same arguments as the ones supplied to emplace, forwarded via std::forward<Args>(args).... And heads up: the element may still be constructed even if there already is an element with the key in the container β€” in that case the newly constructed element is destroyed immediately. πŸ’€

Careful use of emplace lets the new element be constructed while avoiding unnecessary copy or move operations. That’s the whole flex. ✨

If after the operation the new number of elements is greater than old max_load_factor() * bucket_count(), a rehashing takes place. If rehashing occurs (due to the insertion), all iterators are invalidated. Otherwise (no rehashing), iterators are not invalidated. Important vibe check: iterator invalidation is not a drill. 🫢

πŸ’œ Parameters πŸ’œ

  • args β€” the arguments to forward to the constructor of the element.

🌸 Return value 🌸

It returns a std::pair consisting of:

  • an iterator to the inserted element (or to the element that prevented the insertion), and
  • a bool value set to true if and only if the insertion took place.

πŸ’… Exceptions πŸ’…

If an exception is thrown for any reason, this function has no effect. That’s the strong exception safety guarantee, and she ate. πŸ’–

πŸ”₯ Complexity πŸ”₯

Amortized constant on average, worst case linear in the size of the container. So: usually slay, worst case lowkey a little yikes. 😭

πŸŽ€ Example πŸŽ€

This section is incomplete Reason: no example

Not me giving you an empty example section, but that’s literally what the page says. πŸ™ˆ

🌈 See also 🌈

  • emplace_hint β€” constructs elements in-place using a hint (public member function).
  • insert β€” inserts elements or nodes (since C++17) (public member function).

πŸŽ€ Category: πŸŽ€

  • Todo no example

source/version: http://cppreference.com Β· date: 2024.06.10 Β· page label: std::unorde...set::emplace(3) πŸ’œπŸ«Άβœ¨

πŸ“¦ where this page comes from