Get the first and last element of the list | C++ STL

Here, we are going to learn how to access/get the first and last element of a list? To get the first element, we use front() function and to get the last element, we use back() function.
Submitted by IncludeHelp, on October 30, 2018

Given a list with some of the elements, we have to access its first and last elements of the list in C++ (STL) program.

front() and back() function of the list

These are two functions which can be used to get the first and last element of the list. 'front()' returns the first element and 'back()' returns the last element.

Let's implement the program below...

Example:

    Input:
    List: [10, 20, 30, 40, 50]

    Output:
    First element: 10
    Last element: 50

Program:

#include <iostream>
#include <list>
using namespace std;

int main() 
{
	list<int> iList = {10, 20, 30, 40, 50};
	
	cout<<"First element: "<<iList.front()<<endl;
	cout<<"Last element: "<<iList.back()<<endl;
	
	return 0;
}

Output

First element: 10
Last element: 50




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.