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

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


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

Input: set = [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 set. 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 Set by passing its value
#include <iostream>
#include <set>
using namespace std;
// Function to print the set
void printSet(set<int> myset)
    // Get the iterator
    set<int>::iterator it;
    // printing all the elements of the set
    for (it = myset.begin(); it != myset.end(); ++it)
        cout << ' ' << *it;
    cout << '\n';
// Function to delete the element of set
void deleteRange(set<int> myset)
    // printing all the elements of the set
    cout << "\nSet originally: ";
    // Get the starting Iterator at 3rd element
    set<int>::iterator start_itr = myset.begin();
    // Get the ending Iterator at 2nd last element
    set<int>::iterator end_itr = myset.end();
    // Erase the elements in the range
    // of the iterators passed as the parameter
    myset.erase(start_itr, end_itr);
    // printing all the elements of the set
    cout << "Set after deletion of range"
         << " from 3rd till 2nd last: ";
// Driver code
int main()
    set<int> myset;
    // Get the set
    for (int i = 1; i < 10; i++)
        myset.insert(i * 10);
    // Delete an element from the Set
    return 0;

Set originally:  10 20 30 40 50 60 70 80 90
Set 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.

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 :