list pop back() and front() function in c++














































list pop back() and front() function in c++



list::pop_back():This is a built-in function in C++  which is used to remove an element from the back of a list container. That is, this function deletes the last element of a list container. This function thus decreases the size of the container by 1 as it deletes an element from the end of list.

list::pop_front():- This is a built-in function in C++  which is used to remove an element from the front of a list container. This function is same in functioning as pop back but it deletes the element from the front of the list 

Sample program to show use of both function :-

#include <bits/stdc++.h> using namespace std; int main() { // Creating a list list<int> demoList; // Adding elements to the list // using push_back() demoList.push_back(10); demoList.push_back(20); demoList.push_back(30); demoList.push_back(40); // Initial List: cout << "Initial List: "; for (auto itr = demoList.begin(); itr != demoList.end(); itr++) cout << *itr << " "; // removing an element from the end of List // using pop_back demoList.pop_back(); // List after removing element from end cout << "\n\nList after removing an element from end: "; for (auto itr = demoList.begin(); itr != demoList.end(); itr++) cout << *itr << " "; demoList.pop_front(); // List after removing element from front cout << "\n\nList after removing an element from front: "; for (auto itr = demoList.begin(); itr != demoList.end(); itr++) cout << *itr << " "; return 0; }
OUTPUT:-

AS u can see here when we used the pop back func it removed 40 which was at last and when we used the front func it removed 10 which was in starting.


Comments