C++ List Library - back() Function


Advertisements

Description

The C++ function std::list::back() returns a reference to the last element of the list. Calling this function on empty list causes undefined behavior.

Declaration

Following is the declaration for std::list::back() function form std::list header.

C++98

reference back();
const_reference back() const;

Parameters

None

Return value

If list object is constant qualified then method returns constant reference otherwise non constant reference.

Exceptions

Calling this method on empty list causes undefined behavior.

Time complexity

Constant i.e. O(1)

Example

The following example shows the usage of std::list::back() function.

#include <iostream>
#include <list>

using namespace std;

int main(void) {
   list<int> l = {1, 2, 3, 4, 5};

   cout << "Last element of the list is = " << l.back() << endl;

   return 0;
}

Let us compile and run the above program, this will produce the following result −

Last element of the list is = 5
list.htm
Advertisements