How to delete a range of values from the Set using Iterator
Last Updated :
03 Jan, 2019
Given a Set, the task is to delete a range of values from this Set using Iterator.
Example:
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.
Syntax:
iterator erase (const_iterator startPositionIterator_exclusive,
const_iterator endingPositionIterator_inclusive);
Below is the implementation of the above approach:
Program:
#include <iostream>
#include <set>
using namespace std;
void printSet(set< int > myset)
{
set< int >::iterator it;
for (it = myset.begin(); it != myset.end(); ++it)
cout << ' ' << *it;
cout << '\n' ;
}
void deleteRange(set< int > myset)
{
cout << "\nSet originally: " ;
printSet(myset);
set< int >::iterator start_itr = myset.begin();
start_itr++;
start_itr++;
set< int >::iterator end_itr = myset.end();
end_itr--;
end_itr--;
myset.erase(start_itr, end_itr);
cout << "Set after deletion of range"
<< " from 3rd till 2nd last: " ;
printSet(myset);
}
int main()
{
set< int > myset;
for ( int i = 1; i < 10; i++)
myset.insert(i * 10);
deleteRange(myset);
return 0;
}
|
Output:
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
Share your thoughts in the comments
Please Login to comment...