The emplace method in C++ for queues inserts a fresh element after the existing back element, effectively extending the queue. This function is responsible for carrying out the insertion process within the queue.
Syntax
template <class... Args> void emplace (Args&&... args);
Parameters
The "args" parameter passes the input for generating a fresh element. It defines the content of the newly created element, which will be placed at the final position.
Return value
The function serves solely to append new elements and does not provide any output.
Example 1
#include<iostream>
#include<queue>
#include<string>
int main()
{
std::queue<std::string> newqueue;
newqueue.emplace("I am the first line");
newqueue.emplace("I am the second one");
std::cout << "Contents of new queue: \n";
while (!newqueue.empty())
{
std::cout << newqueue.front() << "\n";
newqueue.pop ();
}
return 0;
}
Output:
I am the first line
I am the second one
Example 2
#include<iostream>
#include<queue>
#include<string>
using namespace std;
int main()
{
queue<string> newpqueue;
newpqueue.emplace("portal");
newpqueue.emplace("computer science");
newpqueue.emplace("is a");
newpqueue.emplace("Javacpptutorial");
cout << "newpqueue = " ;
while(!newpqueue.empty( ) )
{
cout<< newpqueue.front() << " ";
newpqueue.pop();
}
return 0 ;
}
Output:
Javacpptutorial is a computer science portal
Complexity
One call is made to the emplace_back.
Data races
All elements within the queue undergo modifications whenever a new element is added, resulting in adjustments to the positions of all other elements accordingly.
Exception Safety
A promise is given that matches the actions carried out on the container object underneath.