std::unorde...mplace_hint(3)

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

πŸ’… std::unordered_map::emplace_hint

okay so bestie, welcome to the C++ Standard Library manual page for std::unordered_map::emplace_hint β€” yes the whole name, it's giving "my full government name" energy πŸŽ€ this one lives in the C++ Standard Libary index and it is so much chiller than it sounds, i promise.


✨ NAME ✨

std::unordered_map::emplace_hint β€” literally the thing this whole page is about, no plot twist 🌸


πŸ¦‹ Synopsis πŸ¦‹

template< class... Args >                                      (since C++11)
iterator emplace_hint( const_iterator hint, Args&&... args );

So what's the vibe? It inserts a new element into the container, and it uses hint as a suggestion for where the element should go πŸ‘€ β€” like, it's a hint, not a command, the container is the main character here.

The constructor of the element type (value_type, that is, std::pair<const Key, T>) gets called with exactly the same arguments as you supplied to the function, forwarded with std::forward<Args>(args).... periodt ✨

And here's the important glow-up detail: 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. so like... pay attention to which one you're in, bestie.


🌈 Parameters 🌈

  • hint β€” an iterator, used as a suggestion as to where to insert the new element 🫢 (again: suggestion. it's a soft launch.)
  • args β€” the arguments to forward to the constructor of the element

πŸ‘‘ Return value πŸ‘‘

You get back an iterator to the inserted element, or to the element that prevented the insertion. so you always get a valid iterator back, which is honestly iconic ⭐


πŸ”₯ Exceptions πŸ”₯

If an exception is thrown for any reason, this function has no effect (strong exception safety guarantee). that's the good stuff, no half-finished mess left behind 🧚


πŸ’œ Complexity πŸ’œ

Amortized constant on average, worst case linear in the size of the container. ngl, that's the whole story.


πŸ’– Example πŸ’–

// Run this code
#include <chrono>
#include <cstddef>
#include <functional>
#include <iomanip>
#include <iostream>
#include <unordered_map>

const int n_operations = 100'500'0;

std::size_t map_emplace()
{
    std::unordered_map<int, char> map;
    for (int i = 0; i < n_operations; ++i)
        map.emplace(i, 'a');
    return map.size();
}

std::size_t map_emplace_hint()
{
    std::unordered_map<int, char> map;
    auto it = map.begin();
    for (int i = 0; i < n_operations; ++i)
    {
        map.emplace_hint(it, i, 'b');
        it = map.end();
    }
    return map.size();
}

std::size_t map_emplace_hint_wrong()
{
    std::unordered_map<int, char> map;
    auto it = map.begin();
    for (int i = n_operations; i > 0; --i)
    {
        map.emplace_hint(it, i, 'c');
        it = map.end();
    }
    return map.size();
}

std::size_t map_emplace_hint_corrected()
{
    std::unordered_map<int, char> map;
    auto it = map.begin();
    for (int i = n_operations; i > 0; --i)
    {
        map.emplace_hint(it, i, 'd');
        it = map.begin();
    }
    return map.size();
}

std::size_t map_emplace_hint_closest()
{
    std::unordered_map<int, char> map;
    auto it = map.begin();
    for (int i = 0; i < n_operations; ++i)
        it = map.emplace_hint(it, i, 'e');
    return map.size();
}

double time_it(std::function<std::size_t()> map_test,
               std::string what = "", double ratio = 0.0)
{
    const auto start = std::chrono::system_clock::now();
    const std::size_t map_size = map_test();
    const auto stop = std::chrono::system_clock::now();
    std::chrono::duration<double, std::milli> time = stop - start;
    if (what.size() && map_size)
        std::cout << std::setw(8) << time << " for " << what << " (ratio: "
                  << (ratio == 0.0 ? 1.0 : ratio / time.count()) << ")\n";
    return time.count();
}

int main()
{
    std::cout << std::fixed << std::setprecision(2);
    time_it(map_emplace); // cache warmup
    const auto x = time_it(map_emplace, "plain emplace");
    time_it(map_emplace_hint, "emplace with correct hint", x);
    time_it(map_emplace_hint_wrong, "emplace with wrong hint", x);
    time_it(map_emplace_hint_corrected, "corrected emplace", x);
    time_it(map_emplace_hint_closest, "emplace using returned iterator", x);
}

🌸 Possible output 🌸

143.48ms for plain emplace (ratio: 1.00)
164.78ms for emplace with correct hint (ratio: 0.87)
171.22ms for emplace with wrong hint (ratio: 0.84)
166.55ms for corrected emplace (ratio: 0.86)
167.41ms for emplace using returned iterator (ratio: 0.86)

lowkey the ratio column is the whole tea β˜• β€” the "wrong hint" one is out here at 0.84 and honestly? relatable.


πŸŽ€ See also πŸŽ€

  • emplace β€” constructs element in-place (public member function)
  • insert β€” inserts elements or nodes (since C++17) (public member function)

🫢 friendly reminder bestie: hint is a suggestion, not a promise, and if a rehash happens your iterators are gone gone. check the max_load_factor() * bucket_count() line before you get attached πŸ’…

okay that's the page!! ily, go read the insert page next, it's the sibling πŸ’œ

β€” with love, from http://cppreference.com, version 2024.06.10 🌈✨ (that's the std::unorde...mplace_hint(3) you're reading, mwah πŸ’‹)

πŸ“¦ where this page comes from