C++ Standard Library C++ STL Library

C++ queue - back() Function



The C++ queue::back function returns a reference to the last 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 last element of the queue will be the most recently added element.

Syntax

reference back();
const_reference back() const;
reference back();
const_reference back() const;

Parameters

No parameter is required.

Return Value

A reference to the last element in the queue.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the queue::back function is used to access the last 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 last element of MyQueue is: ";
  cout<<MyQueue.back();

  cout<<"\n\nAdd a new element to the MyQueue.\n";
  MyQueue.push(500);

  cout<<"Now, The last element of MyQueue is: ";
  cout<<MyQueue.back();  
  return 0;
}

The output of the above code will be:

The last element of MyQueue is: 50

Add a new element to the MyQueue.
Now, The last element of MyQueue is: 500

❮ C++ <queue> Library