C++ Queue::emplace() Function



The C++ std::queue::emplace() function in the queue container allows direct construction of elements in place, rather than copy or move operations. It constructs objects within the queue by forwarding arguments to the constructor of the element type.

Unlike push() function, which takes a pre-constructed object and copies it into the queue, emplace() function constructs the object directly within the queue. The time complexity of this function is logarithmic.

Syntax

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

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

Parameters

  • args − It indicates the argument forwarded to construct the new element.

Return value

This function does not return anything.

Example

Let's look ath the following example, where we are going to emplace a integers into the queue.

#include <iostream>
#include <queue>
int main()
{
    std::queue<int> x;
    x.emplace(11);
    x.emplace(22);
    std::cout << " " << x.front() << std::endl;
    return 0;
}

Output

Following is the output of the above code −

11

Example

Consider the another scenario, where we are going to use the move semantic and inserting a string into the queue.

#include <iostream>
#include <queue>
#include <string>
int main()
{
    std::queue<std::string> x;
    std::string str = "TutorialsPoint";
    x.emplace(std::move(str));
    std::cout << " " << x.front() << std::endl;
    return 0;
}

Output

Output of the above code is as follows −

TutorialsPoint

Example

Following is the example, where we are going to emplace the pairs into the queue.

#include <iostream>
#include <queue>
#include <utility>
int main()
{
    std::queue<std::pair<int, int>> x;
    x.emplace(11, 2);
    x.emplace(3, 44);
    while (!x.empty()) {
        auto a = x.front();
        std::cout << "(" << a.first << ", " << a.second << ") ";
        x.pop();
    }
    return 0;
}

Output

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

(11, 2) (3, 44)
queue.htm
Advertisements