std::priori...ue::emplace(3)

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

πŸ’… NAME

std::priority_queue::emplace β€” like, the emplace of std::priority_queue, bestie πŸ’–

(okay so this page lives in the C++ Standard Libary manual β€” yes, that's their spelling up top, not mine, don't come for me πŸ™ˆ β€” and it's the std::priori...ue::emplace(3) page, the title got cutely truncated by the header, love that for it ✨)


✨ SYNOPSIS ✨

template< class... Args >        (since C++11)
void emplace( Args&&... args );

Okay so real talk: this bad boy pushes a new element to the priority queue. And the way it does it? The element is constructed in-place, which literally means no copy or move operations are performed β€” none, zero, nada 🌸. The constructor of the element gets called with exactly the same arguments you handed to the function, so it's giving "build it right where it lives" main character energy πŸ‘‘

Effectively calls β€” i.e. under the hood it's doing this exact thing:

c.emplace_back(std::forward<Args>(args)...);
std::push_heap(c.begin(), c.end(), comp);

Slay. That's the whole magic trick πŸŽ€


πŸŽ€ PARAMETERS

  • args β€” the arguments to forward to the constructor of the element. Like, you're basically handing the element's constructor its little starter pack 🫢

🌸 RETURN VALUE

(none) β€” nothing, nope, void, she returns nothing and honestly? iconic 😌


πŸ¦‹ COMPLEXITY

Logarithmic number of comparisons πŸ”₯ β€” plus the complexity of Container::emplace_back, so budget for that too, iykyk.


πŸ“ EXAMPLE

// Run this code

#include <iostream>
#include <queue>

struct S
{
    int id;

    S(int i, double d, std::string s) : id{i}
    {
        std::cout << "S::S(" << i << ", " << d << ", \"" << s << "\");\n";
    }
    friend bool operator< (S const& x, S const& y) { return x.id < y.id; }
};

int main()
{
    std::priority_queue<S> queue;
    queue.emplace(42, 3.14, "C++");
    std::cout << "id: " << queue.top().id << '\n';
}

πŸ”₯ OUTPUT

S::S(42, 3.14, "C++")
id = 42

That's literally what the page says, I'm just the messenger πŸ™ˆπŸ’€


🫢 SEE ALSO

  • push β€” inserts element and sorts the underlying container (public member function)
  • pop β€” removes the top element (public member function)

okay that's the whole page bestie, you ate that πŸ“ source is http://cppreference.com, dated 2024.06.10 β€” mwah, go forth and emplace responsibly πŸ’œβœ¨πŸ§š

πŸ“¦ where this page comes from