Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

(C++) std::remove_copy_if

 

Algorithm that IMHO could have better be called std::copy_if_not, as it does not remove anything, and only copies the elements that do not fulfull the predicate.

 

Prefer algorithm calls over hand-written loops [1,2].

 

Example

 

 

#include <algorithm>

#include <list>

#include <iostream>

#include <iterator>

 

struct IsEven : public std::unary_function<bool,int>

{

const bool operator()(const int i) { return i % 2 == 0 ; }

};

 

int main()

{

std::list<int> v;

for (int i=0; i!=10; ++i) v.push_back(i);

 

std::list<int> temp;

std::remove_copy_if(v.begin(),v.end(), std::back_inserter(temp), IsEven() );

 

std::cout << "Content of v:" << std::endl;

std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout," "));

std::cout << "Content of temp:" << std::endl;

std::copy(temp.begin(), temp.end(), std::ostream_iterator<int>(std::cout," "));

 

}

 

 

Screen output

 

Content of v:

0 1 2 3 4 5 6 7 8 9

Content of temp:

1 3 5 7 9

 

 

External links

* SGI's std:: remove_copy_if page

* C++ Reference's std::remove_copy_if page

 

References

[1] Bjarne Stroustrup. The C++ Programming Language (3rd edition).

ISBN: 0-201-88954-4. Chapter 18.12.1: 'Prefer algorithms to loops.

[2] Scott Meyers. Effective STL. ISBN: 0-201-74962-9.

Item 43: 'Prefer algorithm calls over hand-written loops'

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.