Open In App

How to Access the Last Element of a List in C++?

In C++STL, the list container is a doubly-linked list that stores elements in non-contiguous memory locations. In this article, we will learn how to access the last element in a list in C++.

For Example, 

Input:
myList = {10, 20, 80, 90, 50};

Output: 
Last element of the list is : 50

Access the Last Element in a List in C++ 

The simplest and most efficient way to access the last element of a std::list is by using the std::list::back() member function that returns a reference to the last element in the list.

Syntax to Use std::list::back() Function

listName.back()

C++ Program to Access the Last Element in a List

The below example demonstrate the use of the std::list::back() function to access the last element of a std::list in C++ STL.

// C++ program demonstrate the use of the std::list::back()
// function to access the last element of a std::list
#include <iostream>
#include <list>
using namespace std;

int main()
{
    // Creating a list of integers
    list<int> nums = { 10, 20, 80, 90, 50 };

    // Accessing the last element
    int lastElement = nums.back();

    // Printing the last element
    cout << "Last element of the list is : " << lastElement
         << endl;

    return 0;
}

Output
Last element of the list is : 50

Time Complexity: O(1)
Auxiliary Space: O(1)

In the above example, myList.back() returns a reference to the last element in the list myList, and we store it in the variable lastElement. Then, we simply print out the value of lastElement.

Note: We can also use std::list::end() function that returns an iterator pointing to the position after the last element in the list, and then decrement the iterator to point to the last element.




Article Tags :