40 若一个类是函数子,则应是它可配接

例如:
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()的参数和返回类型相同。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值