Given a List, the task is to remove the last element from this List in C++.
Examples:
Input: list = [10 20 30 70 80 90 100 40 50 60]
Output: 10 20 30 40 50 60 70 80 90
Input: list = [1 2 3 4 5]
Output: 1 2 3 4
Lists are a type of associative containers in which each element has to be unique because the value of the element identifies it. The value of the element cannot be modified once it is added to the list, though it is possible to remove and add the modified value of that element.
The last element of the List can be deleted by by passing its iterator.
Syntax:
iterator erase (const_iterator positionOfElementToBeDeleted);
Approach: One can easily delete the last element by passing its iterator to the erase function. To reach the iterator which points to the last element, there are two ways:
- Method 1:
prev(listInt.end())
Below is the implementation of the above approach:
Program 1:
#include <iostream>
#include <list>
using namespace std;
void printList(list< int > mylist)
{
list< int >::iterator it;
for (it = mylist.begin(); it != mylist.end(); ++it)
cout << ' ' << *it;
cout << '\n' ;
}
void deleteByMethod1(list< int > mylist)
{
cout << "\nList originally: " ;
printList(mylist);
list< int >::iterator it;
it = prev(mylist.end());
mylist.erase(it);
cout << "List after deletion: " ;
printList(mylist);
}
int main()
{
list< int > mylist;
for ( int i = 1; i < 10; i++)
mylist.push_back(i * 10);
deleteByMethod1(mylist);
return 0;
}
|
Output:
List originally: 10 20 30 40 50 60 70 80 90
List after deletion: 10 20 30 40 50 60 70 80
- Method 2:
list::iterator it = listInt.end();
--it;
Below is the implementation of the above approach:
Program 2:
#include <iostream>
#include <list>
using namespace std;
void printList(list< int > mylist)
{
list< int >::iterator it;
for (it = mylist.begin(); it != mylist.end(); ++it)
cout << ' ' << *it;
cout << '\n' ;
}
void deleteByMethod2(list< int > mylist)
{
cout << "\nList originally: " ;
printList(mylist);
list< int >::iterator it;
it = --mylist.end();
mylist.erase(it);
cout << "List after deletion: " ;
printList(mylist);
}
int main()
{
list< int > mylist;
for ( int i = 1; i < 10; i++)
mylist.push_back(i * 10);
deleteByMethod2(mylist);
return 0;
}
|
Output:
List originally: 10 20 30 40 50 60 70 80 90
List after deletion: 10 20 30 40 50 60 70 80