English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ Usage and Example of Queue emplace() Function

C++ STL Queue (Queue)

C ++ The emplace() function of the queue adds a new element at the end of the queue, which is the same as push. This function performs an insertion operation on the queue.

Syntax

template<class... Args> void emplace(Args&&... args);

Parameters

argsParameters are forwarded to construct the parameters of the new element. It specifies the value of the newly constructed element, which will be inserted at the end position.

Return value

This function is used only to add new elements and does not return any value.

Instance1

#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 line");
	std::cout << "New queue content: \n";
	while (!newqueue.empty())
	{
		std::cout << newqueue.front() << "\n";
		newqueue.pop();
	}
	return 0;
}

Output:

I am the first line
I am the second line

Instance2

#include<iostream>
#include<queue>
#include<string>
using namespace std;
int main()
{
	queue<string> newpqueue;
	newpqueue.emplace("在线");
	newpqueue.emplace("基础教程");
	newpqueue.emplace("IT");
	newpqueue.emplace("www.oldtoolbag.com");
	cout << "newpqueue = ";
	while(!newpqueue.empty())
	{
		cout << newpqueue.front() << " ";
		newpqueue.pop();
	}
	return 0;
}

Output:

newpqueue = Online Basic Tutorial IT www.oldtoolbag.com

Complex

One call to emplace_back was made.

Data RACE

All elements in the queue are modified because a new element is added, and the corresponding positions of all other elements are also changed.

Exception Safety

It provides guarantees equivalent to operations performed on underlying container objects.

C++ STL Queue (Queue)