In C++, size() returns the number of elements currently stored in a std::priority_queue. A new queue has size 0. Every push() adds one, and every pop() takes one away.
Duplicates count too. If you push the same number three times, the size is 3. The size says nothing about priority. It only counts the elements, so you still use top() to see the largest or most important one.
This function is a member function of std::priority_queue<T>, declared in the <queue> header. It has been available since the first C++ standard, so every compiler supports it. You call it with a dot, for example pq.size(...).
Syntax
Call size() on the queue. It takes no arguments and returns an unsigned number.
C++
std::priority_queue<int> pq;
pq.push(5);
pq.push(9);
std::size_t n = pq.size(); // 2
Call
What it does
pq.size()
Returns how many elements the queue holds. The queue is not changed.
The return type is size_type, an unsigned integer. Be careful when you subtract from it. If the queue is empty, pq.size() - 1 does not give -1. It wraps around to a very large number. Check empty() first.
The queue is a min-heap, so its top() is always the smallest value. That is the one we want to throw away when there are too many.
After each push() the code checks pq.size() > k. When the size reaches 4, pop() drops the smallest value, so the size never stays above 3.
When the loop ends, the three biggest numbers 7, 8, and 9 remain. Draining a min-heap prints them from smallest to largest.
Frequently Asked Questions
It returns the number of elements currently in the priority queue, as an unsigned size_type. An empty queue has size 0.
Yes. A priority_queue keeps every element you push, including equal values. Pushing 5 three times gives a size of 3.
No. Both only read. Only push(), emplace(), pop(), and swap() change the contents of the queue.
Both work, but empty() is clearer and just as fast. Use size() when you need the actual count, for example to keep only the top K values.
size() returns an unsigned type. On an empty queue, 0 - 1 wraps around to a very large number instead of -1. Check empty() first, or compare without subtracting.