C++ STL 函数符

定义函数符

functor.h

  1. #ifndef PRO1_FUNCTOR_H
  2. #define PRO1_FUNCTOR_H
  3. template <class T>
  4. class TooBig {
  5. private:
  6. T cutoff;
  7. public:
  8. TooBig(const T & t):cutoff(t){}
  9. bool operator()(const T & v){ return v > cutoff; }
  10. };
  11. #endif //PRO1_FUNCTOR_H

functor.cpp

  1. #include "functor.h"

函数符的使用

main.cpp

  1. #include <iostream>
  2. #include "module17_stl/functor/functor.h"
  3. using namespace std;
  4. // 函数符
  5. void useFunctor(){
  6. TooBig<int> f100(100);
  7. list<int> yadayada;
  8. list<int> etcetera;
  9. int vals[10] = {50, 100, 90, 180, 60, 210, 415, 88, 188, 201};
  10. yadayada.insert(yadayada.begin(), vals, vals + 10);
  11. etcetera.insert(etcetera.begin(), vals, vals + 10);
  12. ostream_iterator<int, char> out(cout, " ");
  13. cout << "Original list:\n";
  14. copy(yadayada.begin(), yadayada.end(), out);
  15. cout << endl;
  16. copy(etcetera.begin(), etcetera.end(), out);
  17. cout << endl;
  18. yadayada.remove_if(f100);
  19. etcetera.remove_if(TooBig<int>(200));
  20. cout << "Trimmed lists:\n";
  21. copy(yadayada.begin(), yadayada.end(), out);
  22. cout << endl;
  23. copy(etcetera.begin(), etcetera.end(), out);
  24. cout << endl;
  25. }
  26. int main() {
  27. useFunctor();
  28. return 0;
  29. }

程序输出

  1. Original list:
  2. 50 100 90 180 60 210 415 88 188 201
  3. 50 100 90 180 60 210 415 88 188 201
  4. Trimmed lists:
  5. 50 100 90 60 88
  6. 50 100 90 180 60 88 188

自适应函数符和函数适配器

  1. #include <iostream>
  2. #include <functional>
  3. using namespace std;
  4. // funadap-自适应函数符和函数适配器
  5. void Shows(double);
  6. const int LIM = 5;
  7. void Shows(double v){
  8. cout.width(6);
  9. cout << v << ' ';
  10. }
  11. void funadap(){
  12. double arr1[LIM] = {36, 39, 42, 45, 48};
  13. double arr2[LIM] = {25, 27, 29, 31, 33};
  14. vector<double> gr8(arr1, arr1 + LIM);
  15. vector<double> m8(arr2, arr2 + LIM);
  16. cout.setf(ios_base::fixed);
  17. cout.precision(1);
  18. cout << "gr8: \t";
  19. for_each(gr8.begin(), gr8.end(), Shows);
  20. cout << endl;
  21. cout << "m8: \t";
  22. for_each(m8.begin(), m8.end(), Shows);
  23. cout << endl;
  24. vector<double > sum(LIM);
  25. transform(gr8.begin(), gr8.end(), m8.begin(), sum.begin(), plus<double>());
  26. cout << "sum: \t";
  27. for_each(sum.begin(), sum.end(), Shows);
  28. cout << endl;
  29. vector<double > prod(LIM);
  30. transform(gr8.begin(), gr8.end(), prod.begin(), bind1st(multiplies<double>(), 2.5));
  31. cout << "prod:\t";
  32. for_each(prod.begin(), prod.end(), Shows);
  33. cout << endl;
  34. }
  35. int main() {
  36. funadap();
  37. return 0;
  38. }

程序输出

  1. gr8: 36.08224 39.08224 42.08224 45.08224 48.08224
  2. m8: 25.08224 27.08224 29.08224 31.08224 33.08224
  3. sum: 61.08224 66.08224 71.08224 76.08224 81.08224
  4. prod: 90.08224 97.58224 105.08224 112.58224 120.08224