×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

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

Problem statement

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.

Inserting the element at beginning and end 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...

Here is an example with sample input and output:

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

C++ program to insert the element at beginning and end of the list

#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

Comments and Discussions!

Load comments ↻





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