Use member function reference function adaptor : Function Adaptor « Function « C++






Use member function reference function adaptor

Use member function reference function adaptor

#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;

class Numbers {
  int val;
public:
  Numbers() { 
     val = 0; 
  }
  Numbers(int x) { 
     val = x; 
  }

  bool showval() { 
     cout << val << " "; 
     return true; 
  }

  bool isPrime() {
    for(int i = 2; i <= (val/2); i++)
      if(!(val%i)) 
         return false;
    return true;
  }

  bool isEven() { 
     return (bool) !(val % 2); 
  }
  bool isOdd() { 
     return (bool) (val %2); 
  }  
};

int main()
{
  vector<Numbers> vectorObject(10);
  vector<Numbers>::iterator end_p;
  int i;

  for(i = 0; i <10; i++)
    vectorObject[ i ] = Numbers(i+1);

  cout << "Sequence contains: ";
  for_each(vectorObject.begin(), vectorObject.end(), mem_fun_ref(&Numbers::showval));
  cout << endl;

  // remove the primes
  end_p = remove_if(vectorObject.begin(), vectorObject.end(), mem_fun_ref(&Numbers::isPrime));  

  cout << "Sequence after removing primes: ";
  for_each(vectorObject.begin(),  end_p, mem_fun_ref(&Numbers::showval));
  cout << endl;

  for(i = 0; i <10; i++)
    vectorObject[ i ] = Numbers(i + 1);

  
  end_p = remove_if(vectorObject.begin(), vectorObject.end(), mem_fun_ref(&Numbers::isEven));

  cout << "Sequence after removing even values: ";
  for_each(vectorObject.begin(), end_p, mem_fun_ref(&Numbers::showval));
  cout << endl;

  for(i = 0; i < 10; i++)
    vectorObject[ i ] = Numbers(i + 1);

  end_p = remove_if(vectorObject.begin(), vectorObject.end(), mem_fun_ref(&Numbers::isOdd)); 

  cout << "Sequence after removing odd values: ";
  for_each(vectorObject.begin(), end_p, mem_fun_ref(&Numbers::showval));


  return 0;
}


           
       








Related examples in the same category

1.Use a function adaptor in vectorUse a function adaptor in vector
2.Use a unary function object to determine even/odd.Use a unary function object to determine even/odd.