Open In App

How to Delete an Element from a Set in C++?

Last Updated : 26 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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++


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)




Next Article
Article Tags :
Practice Tags :

Similar Reads