list back() function in C++ STL

C++Server Side ProgrammingProgramming

Given is the task to show the working of list back() function in c++.

The list::back() function is a part of the C++ standard template library. It is used to display the last element of any list.

<list> header file should be included before calling this function.

Syntax

List_Name.back();

Parameters

The function does not accept any parameter.

Return Value

The function returns the value of the last element of the list.

Example

Input: Lt.assign(3,10)
Lt.back()
Output: 10

Explanation − The following example shows how we can find the last value of any list by using the back() function. The list Lt is assigned three elements, each with value 10 and when we use the back() function it gives output 10, which will be the last element of list Lt.

Approach used in the below program as follows −

  • First create a list using list<int>.
  • Then assign the list with some values using the assign() function.
  • After that use the back() function to display the last element of the list

Algorithm

Start
Step 1->In function main()
   Declare list Lt
   Call Lt.assign(size,value)
   Call Lt.back()
Stop

Example

 Live Demo

#include<iostream>
#include<list>
using namespace std;
int main() {
   list<int> Lt;
   //assigning size and values to list Lt
   Lt.assign(4,25);
   cout<<"The last element is"<<Lt.back();
   return 0;
}

Output

If we run the above code it will generate the following output −

The last element is 25
raja
Published on 20-Jan-2020 11:45:40
Advertisements