C++ priority_queue::size() Function



The C++ std::priority_queue::size() function is used to determine the number of elements currently stored in the priority_queue. It is member function that returns a value representing the queue size. The size() function is essential for iterating through the queue or for conditions that depend on the number of elements. This time complexity of this function is constant O(1).

Syntax

Following is the syntax for std::priority_queue::size() function.

size_type size() const;

Parameters

This function does not accept any parameter.

Return value

This function returns the total number of elements present in the priority_queue.

Example

Let's look at the following example, where we are going to check whether the priority_queue is empty or not.

#include <iostream>
#include <queue>
int main()
{
    std::priority_queue<int> a;
    if (a.size() == 0) {
        std::cout << "Priority_queue is empty.";
    } else {
        std::cout << "Priority_queue is not empty.";
    }
    return 0;
}

Output

Following is the output of the above code −

Priority_queue is empty.

Example

Consider the following example, where we are going to use the size() to limit the number of elements from priority_queue.

#include <iostream>
#include <queue>
int main()
{
    std::priority_queue<int> a;
    a.push(1);
    a.push(333);
    a.push(22);
    int limit = 2;
    for (int x = 0; x < std::min(a.size(), static_cast<size_t>(limit)); ++x) {
        std::cout << a.top() << " ";
        a.pop();
    }
    return 0;
}

Output

Output of the above code is as follows −

333 22

Example

In the following example, we are going to print the size of priority_queue after inserting each element in a loop.

#include <iostream>
#include <queue>
int main()
{
    std::priority_queue<int> a;
    for (int x = 0; x < 3; ++x) {
        a.push(x * 2);
        std::cout << "Size after inserting " << (x + 1) << " elements: " << a.size() << std::endl;
    }
    return 0;
}

Output

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

Size after inserting 1 elements: 1
Size after inserting 2 elements: 2
Size after inserting 3 elements: 3

Example

Following is the example, where we are going to show that the size of the priority_queue changes after popping an element.

#include <iostream>
#include <queue>
int main()
{
    std::priority_queue<int> a;
    a.push(333);
    a.push(1);
    a.push(22);
    std::cout << "Size of the priority_queue before popping : " << a.size() << std::endl;
    a.pop();
    std::cout << "Size of the priority_queue after popping : " << a.size() << std::endl;
    return 0;
}

Output

Let us compile and run the above program, this will produce the following result −

Size of the priority_queue before popping : 3
Size of the priority_queue after popping : 2
priority_queue.htm
Advertisements