How to Delete an Element from a Set in C++?
Last Updated :
26 Feb, 2024
A set in C++ is a container that stores unique elements in a sorted order. In this article, we will learn how to delete a specific element from a set.
Example:
Input:
mySet = {5, 2, 8, 1, 4}
Element to delete: 2
Output:
mySet = {5, 1, 8, 4}
Delete an Element from a Set in C++
To delete a specific element from a std::set in C++, we can use the std::set::erase() function. This function removes all elements with a certain value from the set. We can also pass it to the iterator if we need.
C++ Program to Delete an Element from a Set in C++
C++
#include <iostream>
#include <set>
using namespace std;
int main()
{
set< int > mySet = { 1, 2, 3, 4, 5 };
cout << "Elements before deletion: " ;
for ( int elem : mySet) {
cout << elem << " " ;
}
cout << endl;
auto it = mySet.find(3);
if (it != mySet.end()) {
mySet.erase(it);
}
cout << "Elements after deletion using iterators: " ;
for ( int elem : mySet) {
cout << elem << " " ;
}
cout << endl;
return 0;
}
|
Output
Elements before deletion: 1 2 3 4 5
Elements after deletion using iterators: 1 2 4 5
Time Complexity: O(log N), where N is the number of elements in the set.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...