functor.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // functor.cpp -- using a functor
  2. #include <iostream>
  3. #include <list>
  4. #include <iterator>
  5. #include <algorithm>
  6. template<class T> // functor class defines operator()()
  7. class TooBig
  8. {
  9. private:
  10. T cutoff;
  11. public:
  12. TooBig(const T & t) : cutoff(t) {}
  13. bool operator()(const T & v) { return v > cutoff; }
  14. };
  15. void outint(int n) {std::cout << n << " ";}
  16. int main()
  17. {
  18. using std::list;
  19. using std::cout;
  20. using std::endl;
  21. using std::for_each;
  22. using std::remove_if;
  23. TooBig<int> f100(100); // limit = 100
  24. int vals[10] = {50, 100, 90, 180, 60, 210, 415, 88, 188, 201};
  25. list<int> yadayada(vals, vals + 10); // range constructor
  26. list<int> etcetera(vals, vals + 10);
  27. // C++0x can use the following instead
  28. // list<int> yadayada = {50, 100, 90, 180, 60, 210, 415, 88, 188, 201};
  29. // list<int> etcetera {50, 100, 90, 180, 60, 210, 415, 88, 188, 201};
  30. cout << "Original lists:\n";
  31. for_each(yadayada.begin(), yadayada.end(), outint);
  32. cout << endl;
  33. for_each(etcetera.begin(), etcetera.end(), outint);
  34. cout << endl;
  35. yadayada.remove_if(f100); // use a named function object
  36. etcetera.remove_if(TooBig<int>(200)); // construct a function object
  37. cout <<"Trimmed lists:\n";
  38. for_each(yadayada.begin(), yadayada.end(), outint);
  39. cout << endl;
  40. for_each(etcetera.begin(), etcetera.end(), outint);
  41. cout << endl;
  42. // std::cin.get();
  43. return 0;
  44. }