How to delete last element from a List in C++ STL

C++Server Side ProgrammingProgramming

Suppose we have one STL list in C++. There are few elements. We have to delete the last element from that list. So if the elements are like [10, 41, 54, 20, 23, 69, 84, 75], then last element is 75. We will see the C++ code to delete last element from list.

Example

 Live Demo

#include<iostream>
#include<list>
using namespace std;
void display(list<int> my_list){
   for (auto it = my_list.begin(); it != my_list.end(); ++it)
   cout << *it << " ";
}
int main() {
   int arr[] = {10, 41, 54, 20, 23, 69, 84, 75};
   int n = sizeof(arr)/sizeof(arr[0]);
   list<int> my_list;
   for(int i = 0; i<n; i++){
      my_list.push_back(arr[i]);
   }
   cout << "List before delete: ";
   display(my_list);
   my_list.pop_back();//delete last element
   cout << "\nList after delete: ";
   display(my_list);
}

Output

List before delete: 10 41 54 20 23 69 84 75
List after delete: 10 41 54 20 23 69 84
raja
Published on 17-Dec-2019 12:51:04
Advertisements