I have forgotten
my Password

Or login with:

  • Facebookhttp://facebook.com/
  • Googlehttps://www.google.com/accounts/o8/id
  • Yahoohttps://me.yahoo.com

remove_if

Removes elements that match a given criterion
+ View version details

Definition

The remove_if() algorithm is defined in the standard header <algorithm> and in the nonstandard backward-compatibility header <algo.h>.

Interface

#include <algorithm>
template < class ForwardIterator, class Predicate >
   ForwardIterator remove_if(
      ForwardIterator first, 
      ForwardIterator last,
      Predicate pred
   );

Parameters:
Parameter Description
first A forward iterator pointing to the position of the first element in the range from which elements are being removed
last A forward iterator pointing to the position one past the final element in the range from which elements are being removed
pred The unary predicate that must be satisfied is the value of an element is to be replaced

Description

Remove_if algorithm removes all elements from a range that returns true using a given predicate.

Removing is done by shifting the elements in the range in such a way that elements to be erased are overwritten. Remove is stable, meaning that the relative order of elements that are not removed is unchanged.

Return Value

The return value is an iterator to the new end of the range.

Complexity

The complexity is linear; there are (last - first) comparisons for equality.
Example:

Example - remove_if algorithm
Problem
The following program demonstrates how to use remove() and remove_if().
Workings
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
 
using namespace std;
 
int main()
{
  vector<int> coll;
 
  INSERT_ELEMENTS(coll,2,6);
  INSERT_ELEMENTS(coll,4,9);
  INSERT_ELEMENTS(coll,1,7);
  PRINT_ELEMENTS(coll,"coll:                  ");
 
  //remove all elements with value 5
  vector<int>::iterator pos;
  pos = remove (coll. begin(), coll.end(),    //range
                     5);                      //value to remove
 
  PRINT_ELEMENTS(coll,"size not changed:      ");
 
  //erase the "removed" elements in the container
  coll. erase (pos, coll.end());
  PRINT_ELEMENTS(coll,"size changed:          ");
 
  //remove all elements less than 4
  coll.erase(remove_if (coll.begin(), coll.end(),       //range
                        bind2nd(less<int>(),4)),  //remove criterion
                        coll.end());
  PRINT_ELEMENTS(coll,"<4 removed: : ");
 
  return 0;
}
Solution
Output:

coll: 2 3 4 5 6 4 5 6 7 8 9 1 2 3 4 5 6 7
size not changed: 2 3 4 6 4 6 7 8 9 1 2 3 4 6 7 5 6 7
size changed: 2 3 4 6 4 6 7 8 9 1 2 3 4 6 7
<4 removed: : 4 6 4 6 7 8 9 4 6 7
References
  • Nicolai M. Josuttis: "The C++ Standard Library"