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

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Top MCQs

Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.