How to Delete an Element from a Set in C++?
Last Updated :
26 Feb, 2024
Improve
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++
// CPP program to delete an element from a Set
#include <iostream>
#include <set>
using namespace std;
// Driver Code
int main()
{
// Creating a set
set<int> mySet = { 1, 2, 3, 4, 5 };
// Printing elements before deletion
cout << "Elements before deletion: ";
for (int elem : mySet) {
cout << elem << " ";
}
cout << endl;
// Deleting element using iterators
auto it = mySet.find(3);
if (it != mySet.end()) {
mySet.erase(it);
}
// Printing elements after deletion
cout << "Elements after deletion using iterators: ";
for (int elem : mySet) {
cout << elem << " ";
}
cout << endl;
return 0;
}
// This code is contributed by Susobhan Akhuli
35
1
// CPP program to delete an element from a Set
2
3
4
using namespace std;
5
6
// Driver Code
7
int main()
8
{
9
// Creating a set
10
set<int> mySet = { 1, 2, 3, 4, 5 };
11
12
// Printing elements before deletion
13
cout << "Elements before deletion: ";
14
for (int elem : mySet) {
15
cout << elem << " ";
16
}
17
cout << endl;
18
19
// Deleting element using iterators
20
auto it = mySet.find(3);
21
if (it != mySet.end()) {
22
mySet.erase(it);
23
}
24
25
// Printing elements after deletion
26
cout << "Elements after deletion using iterators: ";
27
for (int elem : mySet) {
28
cout << elem << " ";
29
}
30
cout << endl;
31
32
return 0;
33
}
34
35
// This code is contributed by Susobhan Akhuli
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)