What is queue.size() in C++?

The queue.size() function in C++ returns the number of elements in the queue. In short, this function is used to get the current size of the queue.

Figure 1 shows the visual representation of the queue.size() function.

Figure 1: Visual representation of queue.size() function

In order to use the queue.size() function, we must include queue in the program, as shown below.

#include <queue>

Syntax

queue_name.size()
// where the queue_name is the name of the queue

Parameter

This function does not require a parameter.

Return value

This function returns the number of elements in the queue. In short, it is used to get the current size of the queue.

Example

#include <iostream>
//header file
#include <queue>
using namespace std;
int main() {
//filled queue
queue<int> queue1;
queue1.push(1);
queue1.push(3);
queue1.push(5);
queue1.push(2);
queue1.push(0);
//queue1 = 1->3->5->2->0
cout<<"The length of queue1: \n"<<queue1.size()<<"\n";
//empty queue
queue<int> queue2;
cout<<"The length of queue2: \n"<<queue2.size();
}