The C++ std::queue::size() function in the queue container is used to return the number of elements currently stored in the queue. It allows efficient tracking of the queue occupancy, helping in making decisions regarding further operations or resource allocation. By invoking this function we can have a count of the elements without altering the queue structure. The time complexity of this function is Constant i.e. O(1).
SyntaxFollowing is the syntax for std::queue::size() function.
size_type size() const;Parameters
It does not accept any parameters.
Return valueThis function returns the total number of elements present in the queue.
ExampleLet's look at the following example, where we are going to retrieve the size of the queue.
#include <iostream> #include <queue> int main() { std::queue<int> x; x.push(10); x.push(20); std::cout << "Queue Size: " << x.size() << std::endl; return 0; }Output
Output of the above code is as follows −
Queue Size: 2Example
Consider the another scenario, where we are going to retrieve the size of the dynamic queue.
#include <iostream> #include <queue> int main() { std::queue<int> a; for(int x = 0; x < 3; ++x) a.push(x * 3); std::cout << "Queue Size: " << a.size() << std::endl; return 0; }Output
Let us compile and run the above program, this will produce the following result −
Queue Size: 3Example
In the following example, we are going to retrieve the size of the queue after performing the pop() function.
#include <iostream> #include <queue> int main() { std::queue<int> x; x.push(1); x.push(222); x.pop(); std::cout << "Queue Size: " << x.size() << std::endl; return 0; }Output
If we run the above code it will generate the following output −
Queue Size: 1Example
Following is the example, where we are going to retrieve the size of an empty queue.
#include <iostream> #include <queue> int main() { std::queue<int> x; std::cout << "Queue Size:" << x.size() << std::endl; return 0; }Output
Output of the above code is as follows −
Queue Size:0
queue.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4