Remove elements from a set in C++

This post covers:

1. How to remove a single element from a set in C++.
2. How to conditionally remove elements from a set in C++ which satisfy a predicate.


 

1. Deleting a single element

Deleting a single element from the set container is very simple in C++. The idea is to pass the given element to the set::erase function which erases it from the set.

 

Download   Run Code

Output:

c b a

 

2. Deleting all elements that satisfies a predicate

We can even conditionally remove elements from a set that satisfy a predicate. The idea is to use iterators to iterate the set and call the unordered_set::erase function if current element matches the condition. Note that calling erase() method while iterating requires special attention since it invalidates the iterator. We can handle this in several ways:

 
1. In C++11 and above, erase() returns an iterator to the next element or to the unordered_set::end if the last element is removed. The idea is to use the return value of erase() for setting iterator to the next element as shown below:

 

Download   Run Code

Output:

c b

 
2. In C++98/03, erase() does not return an iterator to the next element. The workaround is to increment the iterator after it is passed to the erase() but before erase() is executed. This will pass a copy of the iterator to the erase() function and iterator will not be invalidated since it is already incremented before erase() is called.

 

Download   Run Code

Output:

c b

 
3. Another good alternative is to call the erase() function on a duplicate of current iterator after advancing the iterator to the next element. This works exactly like the previous approach where an implicit copy of iterator is passed to the function.

 

Download   Run Code

Output:

c b

 
4. Another solution is to iterate the set and build up a ‘to-be-removed-list’ of iterators to the elements that satisfy the predicate. Then we loop through that list and call set::erase on each iterator.

 

Download   Run Code

Output:

c b

 
Thanks for reading.

Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of