How to Delete Multiple Elements from a Set in C++?
Last Updated :
18 Mar, 2024
In C++, sets are containers that store unique elements in some sorted order. In this article, we will learn how to delete multiple elements from a set using C++.
Example:
Input:
set = {10, 20, 30, 40, 50, 60}
elements_to_delete = {20, 30, 40}
Output:
Elements of set after deletion: 10 50 60
Removing Multiple Elements from a Set in C++
We can delete multiple elements from a set in C++ by passing each value to the std::set::erase() member function of the std::set class. We can use the loop for deleting multiple values.
C++ Program to Delete Multiple Elements from a Set
The below example demonstrates how we can use erase() function to delete multiple elements from a set in C++ STL.
C++
// C++ Program to illustrate how to delete multiple elements
// from a set
#include <iostream>
#include <set>
using namespace std;
int main()
{
// Set and elements to be deleted from a set
set<int> s = { 10, 20, 30, 40, 50, 60 };
set<int> elements_to_delete = { 20, 30, 40 };
// Print the original set
cout << "Original set: ";
for (auto it = s.begin(); it != s.end(); ++it)
cout << *it << " ";
cout << endl;
// Delete elements from the set
for (auto it = elements_to_delete.begin();
it != elements_to_delete.end(); ++it)
s.erase(*it);
// Print the set after deletion
cout << "Set after deletion: ";
for (auto it = s.begin(); it != s.end(); ++it)
cout << *it << " ";
cout << endl;
return 0;
}
OutputOriginal set: 10 20 30 40 50 60
Set after deletion: 10 50 60
Time Complexity: O(K log N), here K is the number of elements to delete and N is the size of the original set.
Auxilliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...