How to Remove an Element from a Set in C++?
Last Updated :
23 Jul, 2025
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 = 56Output:
{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++
// C++ program to remove specific element from a set
#include <iostream>
#include <set>
using namespace std;
// Driver Code
int main()
{
// Create Set with 10 integers
set<int> set
= { 100, 120, 12, 56, 78, 9, 32, 45, 78, 44 };
cout << "Existing Set" << endl;
for (auto element : set) {
cout << element << " ";
}
// Remove 56 from the set using the erase() function
set.erase(56);
cout << endl;
cout << "Final Set" << endl;
for (auto element : set) {
cout << element << " ";
}
return 0;
}
OutputExisting 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)
Explore
C++ Basics
Core Concepts
OOP in C++
Standard Template Library(STL)
Practice & Problems