C++ priority_queue::emplace() Function



The C++ std::priority_queue::emplace() function of the priority queue is used to insert elements. It constructs and inserts a new element directly into the queue, utilizing move semantics to optimize performance. Unlike push() function, it directly forwards argument to the constructor of the element type, allowing for more flexible and efficient element creations. The time complexity of this function is logarithmic.

Syntax

Following is the syntax for std::priority_queue::emplace() function.

void emplace (Args&&... args);

Parameters

  • args − It is the arguments forwarded to construct the new element.

Return value

This function does not return anything.

Example

Let's look at the following example, where we are going to use the emplace() function.

#include <iostream>
#include <queue>
int main()
{
    std::priority_queue<int> a;
    a.emplace(1);
    a.emplace(2);
    a.emplace(11);
    while (!a.empty()) {
        std::cout << a.top() << " ";
        a.pop();
    }
    return 0;
}

Output

Output of the above code is as follows −

11 2 1 

Example

Consider the following example, where we are going to use the emplace() function with pair values.

#include <iostream>
#include <queue>
#include <vector>
int main()
{
    std::priority_queue<std::pair<int, int>> a;
    a.emplace(1, 2);
    a.emplace(2, 3);
    a.emplace(3, 4);
    while (!a.empty()) {
        auto p = a.top();
        std::cout << "(" << p.first << ", " << p.second << ") ";
        a.pop();
    }
    return 0;
}

Output

If we run the above code it will generate the following output −

(3, 4) (2, 3) (1, 2) 

Example

In the following example, we are going to use the emplace() function with tuples.

#include <iostream>
#include <queue>
#include <tuple>
#include <vector>
int main()
{
    std::priority_queue<std::tuple<int, int, int>> x;
    x.emplace(1, 2, 3);
    x.emplace(3, 4, 5);
    while (!x.empty()) {
        auto [a, b, c] = x.top();
        std::cout << "(" << a << ", " << b << ", " << c << ") ";
        x.pop();
    }
    return 0;
}

Output

Following is the output of the above code −

(3, 4, 5) (1, 2, 3)
priority_queue.htm
Advertisements