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

C++ Usage and example of Queue empty() function

C++ STL Queue (Queue)

C ++ The queue empty() function is used to test whether the container is empty. Sometimes, before using all the elements of the container, it is necessary to determine whether the container is empty, in which case the empty() function can be used to make the judgment.

Syntax

bool empty() const;

Parameter

No parameters. This function is used only for testing whether the container is empty, so it does not take any parameters.

Return value

If the container being referenced is empty, this method returns "true", otherwise it returns "false".

Instance1

#include <iostream>
#include <queue>
int main()
{
	std::queue<int> newqueue;
	int result=0;
	for (int j=1; j<=10; j++)
	newqueue.push(j);
	while (!newqueue.empty())
	{
		result += newqueue.front();
		newqueue.pop();
	}
	std::cout << "The result is: " << result;
	return 0;
}

Output:

The result is: 55

Instance2

#include <iostream>
#include <queue>
using namespace std;
int main()
{
	queue<int> newqueue;
	newqueue.push(55);
	if(newqueue.empty())
	{
		cout << "The queue is empty";
	}
	else
	{
		cout << "The queue is not empty";
	}
	return 0;
}

Output:

The queue is not empty

Complex

The complexity of the function is constant.

Data Races

Accesses the container only. By accessing the container, we know whether it is empty and return based on that value.

Exception Safety

Provides guarantees equivalent to operations performed on underlying container objects.

C++ STL Queue (Queue)