queue::empty() and queue::size() in C++ STL

C++ STL queue::empty() and queue::size() function: Here, we are going to learn about empty() and size() function of the queue with the Example.
Submitted by IncludeHelp, on November 27, 2018

In C++ STL, Queue is a type of container that follows FIFO (First-in-First-out) elements arrangement i.e. the elements which inserts first will be removed first. In queue, elements are inserted at one end known as "back" and are deleted from another end known as "front".

1) C++ STL queue::empty() function

empty() function checks weather a queue is an empty queue or not, if a queue is empty i.e. it has 0 elements, the function returns 1 (true) and if queue is not empty, the function returns 0 (false).

Syntax:

    queue_name.empty()

Parameters(s): None

Return type:

  1. Returns 1, if queue is empty
  2. Returns 0, if queue is not empty

Program:

#include <iostream>
#include <queue>
using namespace std;

//Main fubction
int main()
{
	// declaring two queues
	queue<int> Q1;
	queue<int> Q2;

	//inserting elements to Q1
	Q1.push(10);
	Q1.push(20);
	Q1.push(30);

	//checking 
	if(Q1.empty())
		cout<<"Q1 is an empty queue"<<endl;
	else
		cout<<"Q1 is not an empty queue"<<endl;

	if(Q2.empty())
		cout<<"Q2 is an empty queue"<<endl;
	else
		cout<<"Q2 is not an empty queue"<<endl;

	return 0;
}

Output

Q1 is not an empty queue 
Q2 is an empty queue

2) C++ STL queue::size() function

size() returns the total number of elements of a queue or we can say it returns the size of a queue.

Syntax:

    queue_name.size()

Parameter(s): None

Return: total number of elements/size of the queue

Program:

#include <iostream>
#include <queue>
using namespace std;

//Main fubction
int main() 
{
	// declaring two queues
	queue<int> Q1;
	queue<int> Q2;

	//inserting elements to Q1
	Q1.push(10);
	Q1.push(20);
	Q1.push(30);

	cout<<"size of Q1: "<<Q1.size()<<endl;
	cout<<"size of Q2: "<<Q2.size()<<endl;

	return 0;
}

Output

size of Q1: 3
size of Q2: 0 



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.