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,




Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.