Remove copy Elements if They Meet a Criterion : remove « STL Algorithms Modifying sequence operations « C++






Remove copy Elements if They Meet a Criterion

  
#include <algorithm>
#include <functional>
#include <vector>
#include <iostream>

using namespace std;

template <class T>
void print(T& c){
   for( typename T::iterator i = c.begin(); i != c.end(); i++ ){
      std::cout << *i << endl;
   }
}


template<class InputIterator, class OutputIterator, class Predicate >
OutputIterator copy_if( InputIterator start, InputIterator stop,OutputIterator out, Predicate select ){
   while( start != stop ){
      if( select( *start ) )
         *out++ = *start;
      ++start;
   }
   return out;
}

int main( )
{
   const int numbers = 7;
   const int num[numbers] = { -5, 0, 13, 20, 10, 4, -1 };
   vector<int> v1( num, num+numbers );
   print( v1 );

   vector<int> v2( num, num+numbers );
   
   vector<int>::const_iterator v2_copy_end = remove_copy_if( v1.begin(), v1.end(), v2.begin(),not1( bind2nd( greater<int>(), 10 ) ) );

   for( vector<int>::const_iterator i = v2.begin(); i != v2_copy_end;++i )
      cout << *i << " ";
}
  
    
  








Related examples in the same category

1.Use the generic remove algorithm
2.Use std::remove to delete all element in a vector by value
3.Remove an element and then erase that element
4.Combine remove and erase together
5.Remove all instances of '0'
6.remove empty string