定义函数符
functor.h
#ifndef PRO1_FUNCTOR_H#define PRO1_FUNCTOR_Htemplate <class T>class TooBig {private:T cutoff;public:TooBig(const T & t):cutoff(t){}bool operator()(const T & v){ return v > cutoff; }};#endif //PRO1_FUNCTOR_H
functor.cpp
#include "functor.h"
函数符的使用
main.cpp
#include <iostream>#include "module17_stl/functor/functor.h"using namespace std;// 函数符void useFunctor(){TooBig<int> f100(100);list<int> yadayada;list<int> etcetera;int vals[10] = {50, 100, 90, 180, 60, 210, 415, 88, 188, 201};yadayada.insert(yadayada.begin(), vals, vals + 10);etcetera.insert(etcetera.begin(), vals, vals + 10);ostream_iterator<int, char> out(cout, " ");cout << "Original list:\n";copy(yadayada.begin(), yadayada.end(), out);cout << endl;copy(etcetera.begin(), etcetera.end(), out);cout << endl;yadayada.remove_if(f100);etcetera.remove_if(TooBig<int>(200));cout << "Trimmed lists:\n";copy(yadayada.begin(), yadayada.end(), out);cout << endl;copy(etcetera.begin(), etcetera.end(), out);cout << endl;}int main() {useFunctor();return 0;}
程序输出
Original list:50 100 90 180 60 210 415 88 188 20150 100 90 180 60 210 415 88 188 201Trimmed lists:50 100 90 60 8850 100 90 180 60 88 188
自适应函数符和函数适配器
#include <iostream>#include <functional>using namespace std;// funadap-自适应函数符和函数适配器void Shows(double);const int LIM = 5;void Shows(double v){cout.width(6);cout << v << ' ';}void funadap(){double arr1[LIM] = {36, 39, 42, 45, 48};double arr2[LIM] = {25, 27, 29, 31, 33};vector<double> gr8(arr1, arr1 + LIM);vector<double> m8(arr2, arr2 + LIM);cout.setf(ios_base::fixed);cout.precision(1);cout << "gr8: \t";for_each(gr8.begin(), gr8.end(), Shows);cout << endl;cout << "m8: \t";for_each(m8.begin(), m8.end(), Shows);cout << endl;vector<double > sum(LIM);transform(gr8.begin(), gr8.end(), m8.begin(), sum.begin(), plus<double>());cout << "sum: \t";for_each(sum.begin(), sum.end(), Shows);cout << endl;vector<double > prod(LIM);transform(gr8.begin(), gr8.end(), prod.begin(), bind1st(multiplies<double>(), 2.5));cout << "prod:\t";for_each(prod.begin(), prod.end(), Shows);cout << endl;}int main() {funadap();return 0;}
程序输出
gr8: 36.08224 39.08224 42.08224 45.08224 48.08224m8: 25.08224 27.08224 29.08224 31.08224 33.08224sum: 61.08224 66.08224 71.08224 76.08224 81.08224prod: 90.08224 97.58224 105.08224 112.58224 120.08224
