Home »
C++ STL
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
Problem statement
Given a list with some of the elements, we have to access its first and last elements of the list in C++ (STL) program.
Getting the first and last element 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...
Here is an example with sample input and output:
Input:
List: [10, 20, 30, 40, 50]
Output:
First element: 10
Last element: 50
C++ program to get the first and last element of the list
#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