list pop_back() function in C++ STL

C++Server Side ProgrammingProgramming

In this article we will be discussing the working, syntax and examples of list::pop_back() 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 list::pop_back()?

list::pop_back() is an inbuilt function in C++ STL which is declared in <list> header file. pop_back() is used to remove/pop the element from the back or the last of the list container. When we use pop_back then it remove/pops the last element and the element before the last element becomes the last element and the size of the list container is reduced by 1.

Syntax

list_container.pop_back();

This function accepts no parameter.

Return Value

This function returns nothing.

Example

In the below code we have to delete the element from the end of a list using the function pop_back() function.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(){
   //create a list
   list<int> myList;
   //inserting elements to a list
   myList.push_back(4);
   myList.push_back(9);
   myList.push_back(1);
   myList.push_back(3);
   //list before poping out the elements
   cout<<"list elements before deletion : ";
   for (auto i = myList.begin(); i != myList.end(); i++)
      cout << *i << " ";
   //removing elements from the end of a list using pop_back()
   myList.pop_back();
   // List after removing element from end
   cout << "\nList after deleting element from the end: ";
   for (auto i = myList.begin(); i != myList.end(); i++)
      cout << *i << " ";
   return 0;
}

Output

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

list elements before deletion : 4 9 1 3
List after deleting element from the end: 4 9 1

Example

In the below code we have to delete the element from the end of a list using the function pop_back() function and with deleting we are doing product of the numbers in a list.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(){
   list<int> myList;
   int product = 1;
   myList.push_back (40);
   myList.push_back (20);
   myList.push_back (30);
   while (!myList.empty()){
      product*=myList.back();
      myList.pop_back();
   }
   cout<<"The product of elements in my list : "<<product<< '\n';
   return 0;
}

Output

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

The product of elements in my list : 24000
raja
Published on 02-Mar-2020 09:27:12
Advertisements