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

C++Server Side ProgrammingProgramming

In this article we will be discussing the working, syntax and examples of queue::empty() and queue::size() functions in C++ STL.

What is a queue in C++ STL?

Queue is a simple sequence or data structure defined in the C++ STL which does insertion and deletion of the data in FIFO(First In First Out) fashion. The data in a queue is stored in continuous manner. The elements are inserted at the end and removed from the starting of the queue. In C++ STL there is already a predefined template of queue, which inserts and removes the data in the similar fashion of a queue.

What is the queue::empty()?

queue::empty() is an inbuilt function in C++ STL which is declared in  header file. queue::empty() is used to check whether the associated queue container is empty or not. This function returns either true or false, if the queue is empty (size is 0) then the function returns true, else if the queue is having some value then it will return false.

Syntax

myqueue.empty();

This function accepts no parameter

Return value

This function returns true if the size of the associated queue container is 0, else will return false.

Example

Input: queue<int> myqueue = {10, 20, 30, 40};
      myqueue.empty();
Output:
      False
Input: queue<int> myqueue;
      myqueue.empty();
Output:
      True

Example

 Live Demo

#include <iostream>
#include <queue>
using namespace std;
int main(){
   queue<int> Queue;
   Queue.push(10);
   Queue.push(20);
   Queue.push(30);
   Queue.push(40);
   //check is queue is empty or not
   if (Queue.empty()){
      cout<<"Queue is empty";
   }
   else{
      cout <<"Queue is not empty";
   }
   return 0;
}

Output

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

Queue is not empty

What is queue::size()?

queue::size() is an inbuilt function in C++ STL which is declared in <queue> header file. queue::size() is used to check whether the size of the associated queue container. This function returns an unsigned int value, i.e the size of the queue container, or the number of elements present in a queue container. This function returns 0 if the queue is empty or having no elements in it.

Syntax

myqueue.size();

This function accepts no parameter

Return value

This function returns unsigned int, the size of the queue container associated with the function.

Example

Input: queue<int> myqueue = {10, 20 30, 40};
      myqueue.size();
Output:
      4
Input: queue<int> myqueue;
      myqueue.size();
Output:
      0

Example

 Live Demo

#include <iostream>
#include <queue>
using namespace std;
int main(){
   queue<int> Queue;
   Queue.push(10);
   Queue.push(20);
   Queue.push(30);
   Queue.push(40);
      cout<<"size of Queue is : "<<Queue.size();
   return 0;
}

Output

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

size of Queue is : 4
raja
Published on 06-Mar-2020 11:45:05
Advertisements