std::queue in C++ is a container adapter that follows the First In First Out (FIFO) principle, where elements are inserted at the rear and removed from the front. The front() and back() member functions provide access to the elements at both ends of the queue.
- front() returns a reference to the first element that will be removed next.
- back() returns a reference to the most recently inserted element.
queue::front() in C++
The front() function is used to access the first element stored in the queue. Since a queue follows the First In First Out (FIFO) principle, front() always returns the element that was inserted earliest and is next to be removed.
- Returns a reference to the first (oldest) element present in the queue.
- Allows access to the front element without removing it from the container.
- Since it returns a reference, the value of the front element can also be modified.
- Calling front() on an empty queue results in undefined behavior.
#include <iostream>
#include <queue>
using namespace std;
int main()
{
queue<int> q;
q.push(3);
q.push(4);
q.push(1);
q.push(7);
cout << q.front();
return 0;
}
Output
3
Syntax
queue_name.front();
- Parameters: This function does not take any parameters.
- Return Value: Returns a reference to the first element of the queue.
queue::back() in C++
The back() function is used to access the last element stored in the queue. It returns the most recently inserted element while preserving the FIFO ordering of the queue.
- Returns a reference to the last (newest) element present in the queue.
- Provides access to the back element without removing it from the container.
- Since it returns a reference, the value of the last element can also be modified.
- Calling back() on an empty queue results in undefined behavior.
#include <iostream>
#include <queue>
using namespace std;
int main()
{
queue<int> q;
q.push(3);
q.push(4);
q.push(1);
q.push(7);
cout << q.back();
return 0;
}
Output
7
Syntax
queue_name.back();
- Parameters: This function does not take any parameters.
- Return Value: Returns a reference to the last element of the queue.
Example: Using front() and back() Together
The following example finds the absolute difference between the first and last elements of a queue.
#include <iostream>
#include <queue>
using namespace std;
int main()
{
queue<int> q;
q.push(1);
q.push(2);
q.push(3);
q.push(4);
q.push(5);
q.push(6);
q.push(7);
q.push(8);
cout << abs(q.back() - q.front());
return 0;
}
Output
7
Explanation: Here, the first element is 1 and the last element is 8, so the difference is: 8 - 1 = 7
Difference Between queue::front() and queue::back()
| Feature | queue::front() | queue::back() |
|---|---|---|
| Returns | First element | Last element |
| Accesses | Oldest element | Newest element |
| Parameters | None | None |
| Return Type | Reference to front element | Reference to back element |
| Time Complexity | O(1) | O(1) |
| Header File | <queue> | <queue> |