public member function template

std::forward_list::remove_if

<forward_list>
template <class Predicate>
  void remove_if ( Predicate pred );
Remove elements fulfilling condition
Removes from the container all the elements for which Predicate pred returns true. This calls the destructor of these objects and reduces the container size by the number of elements removed.

Predicate pred can be implemented as any typed expression taking one argument of the same type as the elements container in the forward_list and returning a bool (this may either be a function pointer or an object whose class implements operator()).

The function calls pred(*i) for each element (where i is an iterator to that element). Any of the elements in the list for which this returns true, is removed from the container.

Notice that a global algorithm function, remove_if, exists with a similar behavior but operating on a range (between two iterators).

Parameters

pred
Unary predicate that, taking a value of the same type as those contained in the forward_list object, returns true for those values to be removed from the container, and false for those remaining.

Return value

none

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// forward_list::remove_if
#include <iostream>
#include <forward_list>

// a predicate implemented as a function:
bool single_digit (const int& value) { return (value<10); }

// a predicate implemented as a class:
class is_odd_class
{
public:
  bool operator() (const int& value) {return (value%2)==1; }
} is_odd_object;

int main ()
{
  std::forward_list<int> mylist = {7, 80, 7, 15, 85, 52, 6};

  mylist.remove_if (single_digit);      // 80 15 85 52

  mylist.remove_if (is_odd_object);     // 80 52

  std::cout << "mylist contains:";
  for (int& x: mylist) std::cout << " " << x;
  std::cout << std::endl;

  return 0;
}


Output:
mylist contains: 80 52

Complexity

Linear in container size (predicate applications).

Iterator validity

All the iterators, pointers and references to elements that have not been removed remain valid after the operation and refer to the same elements they were referring to before.

See also