How to Remove an Element from a Set in C++?
Last Updated :
26 Feb, 2024
In C++, sets are a type of associative container in which each element has to be unique. The values are stored in a specific sorted order i.e. either ascending or descending. In this article, we will see how to remove specific elements from a set in C++.
Example
Input:
set = {100,120,12,56,78,9,32,45,78,44}
Deleting element = 56
Output:
{100,120,12,78,9,32,45,78,44}
Delete a Specific Element from a Set in C++
To delete a specific element from a set in C++, we can use the std::set::erase() function that is able to remove elements by using the value or iterator.
C++ Program to Remove an Element from a Set
C++
#include <iostream>
#include <set>
using namespace std;
int main()
{
set< int > set
= { 100, 120, 12, 56, 78, 9, 32, 45, 78, 44 };
cout << "Existing Set" << endl;
for ( auto element : set) {
cout << element << " " ;
}
set.erase(56);
cout << endl;
cout << "Final Set" << endl;
for ( auto element : set) {
cout << element << " " ;
}
return 0;
}
|
Output
Existing Set
9 12 32 44 45 56 78 100 120
Final Set
9 12 32 44 45 78 100 120
Time complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...