C++ queue - front() Function
The C++ queue::front function returns a reference to the first element of the queue. In a queue, addition of a new element occurs from the back end and deletion of an element occurs from the front end. Hence, The first element of the queue will be the oldest added element.
Syntax
reference front(); const_reference front() const;
reference front(); const_reference front() const;
Parameters
No parameter is required.
Return Value
A reference to the first element in the queue.
Time Complexity
Constant i.e, Θ(1).
Example:
In the example below, the queue::front function is used to access the first element of the queue MyQueue.
#include <iostream> #include <queue> using namespace std; int main (){ queue<int> MyQueue; MyQueue.push(10); MyQueue.push(20); MyQueue.push(30); MyQueue.push(40); MyQueue.push(50); cout<<"The first element of MyQueue is: "; cout<<MyQueue.front(); cout<<"\n\nDelete the oldest element of the MyQueue.\n"; MyQueue.pop(); cout<<"Now, The first element of MyQueue is: "; cout<<MyQueue.front(); return 0; }
The output of the above code will be:
The first element of MyQueue is: 10 Delete the oldest element of the MyQueue. Now, The first element of MyQueue is: 20
❮ C++ <queue> Library