How to delete a range of values from the List using Iterator

Given a List, the task is to delete a range of values from this List using Iterator.


Input: list = [10 20 30 40 50 60 70 80 90],
       start_iterator = 3,
       end_iterator = 8
Output: 10 20 80 90

Input: list = [1 2 3 4 5]
       start_iterator = 1,
       end_iterator = 3
Output: 3 4 5

Approach: In this method, a range of elements are deleted from the list. This is done with the help of two iterators. The first iterator points at the starting element of the range and the second iterator points at the last element of the range. The first iterator is exclusive while the last iterator is inclusive which means that element will also get deleted which is pointed by the last iterator.


iterator erase (const_iterator startPositionIterator_exclusive, 
                const_iterator endingPositionIterator_inclusive);

Below is the implementation of the above approach:






// C++ program to delete an element
// of a List by passing its value
#include <iostream>
#include <list>
using namespace std;
// Function to print the list
void printList(list<int> mylist)
    // Get the iterator
    list<int>::iterator it;
    // printing all the elements of the list
    for (it = mylist.begin(); it != mylist.end(); ++it)
        cout << ' ' << *it;
    cout << '\n';
// Function to delete the element of list
void deleteRange(list<int> mylist)
    // Printing all the elements of the list
    cout << "\nList originally: ";
    // Get the starting Iterator at 3rd element
    list<int>::iterator start_itr = mylist.begin();
    // Get the ending Iterator at 2nd last element
    list<int>::iterator end_itr = mylist.end();
    // Erase the elements in the range
    // of the iterators passed as the parameter
    mylist.erase(start_itr, end_itr);
    // Printing all the elements of the list
    cout << "List after deletion of range"
         << " from 3rd till 2nd last: ";
// Driver Code
int main()
    list<int> mylist;
    // Get the list
    for (int i = 1; i < 10; i++)
        mylist.push_back(i * 10);
    // Delete an element from the List
    return 0;



List originally:  10 20 30 40 50 60 70 80 90
List after deletion of range from 3rd till 2nd last:  10 20 80 90

Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at to report any issue with the above content.