List pop_front() function in C++ STL


In this article we will be discussing the working, syntax and examples of pop_front () function in C++.

What is a List in STL

List is a data structure that allows constant time insertion and deletion anywhere in sequence. Lists are implemented as doubly linked lists. Lists allow non-contiguous memory allocation. List perform better insertion extraction and moving of element in any position in container than array, vector and deque. In List the direct access to the element is slow and list is similar to forward_list, but forward list objects are single linked lists and they can only be iterated forwards.

What is pop_front()

pop_front() is an inbuilt function in C++ STL which is declared in header file. pop_front() is used to pop (delete) the element from the beginning of the list container. The function deletes the first element of the list container, means the second element of the container becomes the first element and the first element from the container is removed from the container. This function decreases the size of the container by 1.

Syntax

void pop_front ();

This function accepts no parameter

Return Value

This function returns nothing, just removes/pops the first element from the container.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(){
   //create a list
   list<int> myList;
   //inserting elements to the list
   myList.push_back(1);
   myList.push_back(2);
   myList.push_back(3);
   myList.push_back(4);
   //List before applying pop_front() function
   cout<<"List contains : ";
   for(auto i = myList.begin(); i != myList.end(); i++)
      cout << *i << " ";
   //removing first element using pop_front()
   myList.pop_front();
   // List after removing element from front
   cout<<"\nList after removing an element from front: ";
   for (auto i = myList.begin(); i != myList.end(); i++)
      cout << *i << " ";
   return 0;
}

Output

If we run the above code then it will generate the following output

List contains : 1 2 3 4
List after removing an element from front: 2 3 4

Example

 Live Demo

#include <iostream>
#include <list>
int main (){
   std::list<int> myList;
   myList.push_back (10);
   myList.push_back (20);
   myList.push_back (30);
   std::cout<<"removing the elements in a list : ";
   while (!myList.empty()){
      std::cout << ' ' << myList.front();
      myList.pop_front();
   }
   std::cout<<"\nSize of my empty list is: " << myList.size() << '\n';
   return 0;
}

Output

If we run the above code then it will generate the following output

removing the elements in a list : 10 20 30
Size of my empty list is: 0

Updated on: 26-Feb-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements