先看下algorithm中提供的查找函数find_if的定义(find_if是find的加强版)
template<class InputIterator, class Predicate> InputIterator find_if( InputIterator _First, InputIterator _Last, Predicate _Pred );
find的函数原型,就是第三个参数又函数对象Predicate变成查找对象值而已。
template<class InputIterator, class Type> InputIterator find( InputIterator _First, InputIterator _Last, const Type& _Val );
上面template说明的class Predicate就是我们要说的函数对象
这里的函数对象可以是一个单纯的一个函数
也可以一个函数对象类
分别举个例子
// alg_find_if.cpp // compile with: /zct #include <vector> #include <algorithm> #include <iostream> using namespace std; bool greater10(int value) { return value >10; } class greater { public: greater(int level):_level(level){} bool operator()(int value){return value>_level;} private: int _level; }; int main() { vector<int> v1; vector<int>::iterator Iter; v1.push_back(10); v1.push_back(20); v1.push_back(10); v1.push_back(40); v1.push_back(10); cout << "v1 = ( "; for (Iter = v1.begin(); Iter != v1.end(); Iter++) cout << *Iter << " "; cout << ")" << endl; vector<int>::iterator result1; result1 = find_if(v1.begin(), v1.end(), greater10); if(result1==v1.end()) cout<<"can't find any elements greater than 10."; else cout << "The number of elements in v1 greater than 10 is: " << *result1 << "." << endl; result1=find_if(v1.begin(),v1.end(),greater(10)); if(result1==v1.end()) cout<<"can't find any elements greater than 10."; else cout << "The number of elements in v1 greater than 10 is: " << *result1 << "." << endl; return 0; }
直接使用函数作为查找判断,如上面定义greater10函数,这个函数一定要返回true或false,接收的参数为查找序列中存放数据的类型
使用函数对象类。上面定义的class greater 函数对象类一定要重载operator(),并且返回true或false,接收的参数为查找序列中存放数据的类型
可以通过构造函数来传递相应的数据。如上面的greater可以通过构造函数传递要判断大于多少的数。
algorithm中很多的函数都有相识的处理
比如count和count_if
如果是使用仿函数,记得调用的时候后面要带括号,如上面的greater(10),没参数时也要括号的,使用回调函数则不需要
用于比较的谓词函数,其参数返回的值还有更进一步的要求,如下面文章所述。(就是两个参数兑换,得到返回的结果必须不同)
http://blog.youkuaiyun.com/clever101/archive/2010/02/22/5317983.aspx
更详细关于回调函数(callback function)和仿函数(functor)的区别请看(也就是上面说的使用函数和函数对象类)
http://blog.youkuaiyun.com/lijgame/archive/2007/03/06/1521753.aspx
上面这篇文章讲的比较升入,如何区别对待这两种函数的使用..