例如:
list<Widget*> widgetPtr;
bool isInteresting(const Windget* pw);
//若想找到第一个满足isInteresting条件的Widget指针:
list<Widget*>::iterator it = find_if(widgetPtr.begin(),widgetPtr.end(),
isInteresting);
if(it != widgetPtr.end())
{
...
}
//若想找到第一个不满足isInteresting条件的Widget指针:
list<Widget*>::iterator it = find_if(widgetPtr.begin(),widgetPtr.end(),
not1(ptr_fun(isInteresting))); //使用ptr_fun来配接
STL有4个标准的函数配接器:
not1 针对一个参数的函数子求反
not2 针对两个参数的函数子求反
bind1st 针对两个参数的函数对象,绑定第一个参数,第二参数为默认的迭代器指向的对象
bind2nd 针对两个参数的函数对象,绑定第二个参数,第一参数为默认的迭代器指向的对象
所谓 bind1st bind2st 参数绑定,指operator()(...)有二个参数时,指定其中一个绑定,另一个就
是*iterator传入;当没有参数或只有一个参数时默认传入的就是*Iterator。所以不需要绑定。
bind1st bind2nd的用法:
template<typename T>
class Meetsthreshold:public std::unary_function<Widget,bool>{
private:
const T threshold;
public:
MeetsThreshold(const T& threshold);
bool operator()(const Widget&)const; //一个参数,不需要绑定
....
};
struct WidgetNameCompare:
public std::binary_function<Widget,Widget,bool>{
bool operator()(const Widget& lhs,const Widget& rhs)const; //二个参数,需要绑一个
};
//找到最后一个不符合阈值是10 的Widget
list<Widget>widgets;
list<Widget>::reverse_iterator i1 = find_if(widgets.rbegin(),widgets.rend(),not1(Meetsthreshold<int>(10)));
//找到按WidgetNameCompare定义的规则排序时,在w之前的第一个widget对象
Widget w(...);
list<Widget>::iterator i2 =
find_if(widgets.begin(),widgets.end(),bind2nd(WidgetNameCompare(),w));
一般情况下,传递给unary_function或binary_function的非指针类型需要去掉const和引用部分;
对于指针作为参数或者返回类型函数子类,一般的规则是传递给nnary_function或binary_function类型与operator()的参数和返回类型相同。