How to Delete an Element from a Set in C++?
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++
// 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 |
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)