Insert the element at beginning and end of the list | C++ STL

Here, we are going to learn how to insert an element at the beginning and an element at the end of the list using C++ STL? Functions push_front() and push_back() are used to insert the element at front and back to the list.
Submitted by IncludeHelp, on October 30, 2018

Given a list with some of the elements, we have to insert an element at the front (beginning) and an element at the back (end) to the list in C++ (STL) program.

Push_front() and push_back() functions of the list

These are two functions which can be used to insert the element at the front and at the end to the list. push_front() inserts the element at the front and push_back() inserts the element at the back (end).

Let's implement the program below...

Example:

    Input:
    List: [10, 20, 30, 40, 50]
    Element to insert at front: 100
    Element to insert at back: 200

    Output:
    List is:
    100
    10
    20
    30
    40
    50
    200

Program:

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

int main() 
{
	//declaring aiList
	list<int>iList = {10, 20, 30, 40, 50};
	//declaring iterator to the list
	list<int>::iterator l_iter; 

	//inserting element at the front
	iList.push_front(100);
	//inserting element at the back
	iList.push_back(200);

	//printing list elements
	cout<<"List elements are"<<endl;
	for (l_iter = iList.begin(); l_iter != iList.end(); l_iter++)
		cout<< *l_iter<<endl;

	return 0;
}

Output

List elements are
100
10 
20 
30 
40 
50 
200

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.