In this article we will discuss how to remove an element from a List by matching a value or by matching some criterion.

std::list provides two member functions for removing elements based on value i.e. std::list::remove and std::list::remove_if.

Using std::list::remove to remove element by value

It removes all the elements from a list that matches the passed element val. Lets see an example, in which we will delete all the occurrences of 4 from a list i.e.

Output:

To compile the above code use following command,

g++ –std=c++11 example.cpp

Using std::list::remove_if to remove elements from a List based on Criterion

In previous example we deleted all the elements from a List that matched the passed values. But this might not be the requirement every time. Many times we need to delete certain elements from a list based on certain criterion Like,

Deleting all elements which are greater than 2 but less than 5 from the list.

To achieve this kind of deletion where every element of list need to verified against a criterion, we will use an another member function of std::list i.e.

std::list::remove_if accepts a Callback inform of a Predicate as an argument. Then it iterates over all the elements from the list and call our Predicate on each of them. Elements for which Predicate returns true, will get deleted from the list.

 

Here, this Predicate is a Callback, that can be,

  • Function Pointer
  • Function Object
  • Lambda Function

Lets see how to delete all elements from a list whose value is greater than or equal to 2 but less than 5 using remove_if & lambda function,

Output:

To Compile the above code use following command,

g++ –std=c++11 example.cpp

Thanks.

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