C++ Standard Library C++ STL Library

C++ <deque> - back() Function



The C++ deque::back function returns a reference to the last element of the deque. Please note that, Unlike the deque::rbegin function, which returns the reverse iterator pointing to the last element, it returns the a direct reference to the same element of the deque.

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 of the deque.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the deque::back function is used to access the last element of the deque MyDeque.

#include <iostream>
#include <deque>
using namespace std;
 
int main (){
  deque<int> MyDeque{10, 20, 30, 40, 50};

  cout<<"The last element of MyDeque is: ";
  cout<<MyDeque.back();

  cout<<"\n\nAdd 100 to the last element of the MyDeque.\n";
  MyDeque.back() = MyDeque.back() + 100;

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

The output of the above code will be:

The last element of MyDeque is: 50

Add 100 to the last element of the MyDeque.
Now, The last element of MyDeque is: 150

❮ C++ <deque> Library