In this article we will discuss how to erase elements from a set while iterating over it.

Erasing elements from std::set while Iterating

std::set provides a member function erase() that accepts an iterator as an argument and deletes it from the set i.e.

But it makes the passed iterator invalid. From c++11 onward it returns an iterator that points to the element next to last deleted element. We can use this for further iteration.

Let’s see an example,

Suppose we have a set of strings i.e.

Now lets remove all string entries from string whose length is greater than 3 i.e.

Complete example is as follows,


Creating generic erase_if for std::set

Let’s create a generic function that can be used with set, vector or list to remove elements while iterating based on some condition i.e.

Now let’s use the above generic function to erase all string from set whose size is greater than 2 i.e.

Complete example is as follows,




Click Here to Subscribe for more Articles / Tutorials like this.