C++ Standard Library C++ STL Library

C++ queue - size() Function



The C++ queue::size function is used to find out the total number of elements in the queue.

Syntax

size_type size() const;
size_type size() const noexcept;

Parameters

No parameter is required.

Return Value

Number of elements present in the queue.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the queue::size function is used find out the total number of elements in a queue called MyQueue.

#include <iostream>
#include <queue>
using namespace std;
 
int main (){
  queue<int> MyQueue;

  //add elements in the queue
  MyQueue.push(10);
  MyQueue.push(20);
  MyQueue.push(30);
  MyQueue.push(40);
  MyQueue.push(50);

  cout<<"Queue size is: "<<MyQueue.size()<<"\n";

  cout<<"Three elements are added in the Queue.\n";
  MyQueue.push(60);
  MyQueue.push(70);
  MyQueue.push(80);

  cout<<"Now, Queue size is: "<<MyQueue.size()<<"\n";
  return 0;
}

The output of the above code will be:

Queue size is: 5
Three elements are added in the Queue.
Now, Queue size is: 8

❮ C++ <queue> Library