How to delete last element from a set in C++
Given a Set, the task is to remove the last element from this Set in C++.
Examples:
Input: set = [10 20 30 70 80 90 100 40 50 60]
Output: 10 20 30 40 50 60 70 80 90
Input: set = [1 2 3 4 5]
Output: 1 2 3 4
Sets 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 set, though it is possible to remove and add the modified value of that element.
The last element of the Set 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(setInt.end())
Below is the implementation of the above approach:
Program 1:
#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 deleteByMethod1(set< int > myset)
{
cout << "\nSet originally: " ;
printSet(myset);
set< int >::iterator it;
it = prev(myset.end());
myset.erase(it);
cout << "Set after deletion: " ;
printSet(myset);
}
int main()
{
set< int > myset;
for ( int i = 1; i < 10; i++)
myset.insert(i * 10);
deleteByMethod1(myset);
return 0;
}
|
Output:
Set originally: 10 20 30 40 50 60 70 80 90
Set after deletion: 10 20 30 40 50 60 70 80
- Method 2:
set::iterator it = setInt.end();
--it;
Below is the implementation of the above approach:
Program 2:
#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 deleteByMethod2(set< int > myset)
{
cout << "\nSet originally: " ;
printSet(myset);
set< int >::iterator it;
it = --myset.end();
myset.erase(it);
cout << "Set after deletion: " ;
printSet(myset);
}
int main()
{
set< int > myset;
for ( int i = 1; i < 10; i++)
myset.insert(i * 10);
deleteByMethod2(myset);
return 0;
}
|
Output:
Set originally: 10 20 30 40 50 60 70 80 90
Set after deletion: 10 20 30 40 50 60 70 80
Last Updated :
06 Dec, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...