VOOZH about

URL: https://www.geeksforgeeks.org/cpp/priority_queueempty-priority_queuesize-c-stl/

⇱ priority_queue::empty() and priority_queue::size() in C++ STL - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 1 Jun, 2023

Priority queues are a type of container adaptors, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue. However, in C++ STL (by default) the largest element is at the top. We can also create a priority queue having the smallest element at the top by simply passing an extra parameter while creating the priority queue.

priority_queue::empty()

empty() function is used to check if the priority queue container is empty or not. 

Syntax :

Time complexity: O(1)

pqueuename.empty()
Parameters :
No parameters are passed
Returns :
True, if priority queue is empty, 
False, Otherwise

Examples:

Input : pqueue = 3, 2, 1
 pqueue.empty();
Output : False

Input : pqueue
 pqueue.empty();
Output : True

Errors and Exceptions 

1. Shows error if a parameter is passed 
2. Shows no exception throw guarantee. 

Output:

False

Application : Given a priority queue of integers, find the sum of the all the integers.

Input : 8, 6, 3, 2, 1 
Output : 20

Algorithm 

1. Check if the priority queue is empty, if not add the top element to a variable initialised as 0, and pop the top element. 
2. Repeat this step until the priority queue is empty. 
3. Print the final value of the variable. 

Output:

20
priority_queue::size()

size() function is used to return the size of the priority queue container or the number of elements in the container.

Time complexity: O(1)

 Syntax :

pqueuename.size()
Parameters :
No parameters are passed
Returns :
Number of elements in the container

Examples:

Input : pqueue = 3, 2, 1
 pqueue.size();
Output : 3

Input : pqueue
 pqueue.size();
Output : 0

Errors and Exceptions 

1. Shows error if a parameter is passed. 
2. Shows no exception throw guarantee 

Output:

5

Application : Given a priority queue of integers, find the sum of the all the integers.

Input : 8, 6, 3, 2, 1 
Output : 20

Algorithm 

1. Check if the size of the priority queue is 0, if not add the top element to a variable initialised as 0, and pop the top element. 
2. Repeat this step until the sizeof the priority queue becomes 0. 
3. Print the final value of the variable. 

Output:

20

Let us see the differences in a tabular form -:

priority_queue::empty()priority_queue::size()
1.It is used to check whether the priority_queue is emptyIt is used to return the number of elements in the priority_queue.
2.

Its syntax is -:

 empty();

Its syntax is -:

size();

3.It does not take any parameters.It does not take any parameters.
4.Its return type is boolean.Its return type is an integer.
5.Its complexity is constant.Its complexity is constant.
Comment