Home »
C++ STL
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