Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


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

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 list.

Time Complexity

Constant i.e, Θ(1)

Example:

In the below example, the list::back function is used to access the last element of the list called MyList.

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

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

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

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

The output of the above code will be:

The last element of MyList is: 50

Add 100 to the last element of the MyList.

Now, The last element of MyList is: 150

❮ C++ <list> Library