使用函数对象(侯捷先生译为伪函数)实现二叉查找树

以前看过《C++标准程序库》,所以乘此机会小复习下。
什么是伪函数?
伪函数是范型编程强大威力和纯粹抽象概念的又一个例证。你可以这么说,任何东西,只要其行为像函数,它就是个函数。因此,如果你定义了一个对象,行为向函数,它就可以被当作函数来用。好,那么什么才算是具备函数行为?所谓函数行为,是指可以”使用小括号传递参数,来调用某个东西”。例如:
function(arg1,arg2); //a function call
如果你指望对象也可以如此这般,就必须让他们也有可能被“调用”——通过小括号的运用和参数的传递。你只需要定义operator(),并给予合适的参数型别:

      class X{
      public:
          //define '' function call '' operator
           return-value operator() ( arguments) const;
      };

现在,你可以把这个类别的对象当作函数来调用了:
X fo;
……
fo(arg1,arg2); // call operator( ) for function object fo
上述调用等同于:
fo.operator() (arg1,arg2);

下面使用函数对象实现二叉查找树的示例

template <typename Object,typename Comparator=less<Object> >
class BinarySearchTree
{
  public:
      // Same method , with Object replacing Comparable 
  private:
    BinaryNode * root;
    Comparator isLessThan;
    //Same methods, with Object replacing Comparable
    /**
    * Internal methods to test if an item is in a subtree.
    * x is item to search for.
    * t is the node that roots the subtree.
    * /
    bool contains(const object & x, BinaryNode * t) const
    {
        if( t == NULL)
            return false;
        else if ( isLessThan(x, t->element)
            return  contains(x,t->left);
        else if ( isLessThan(t->element ,x ) )
            return contains(x,t->right);
        else
            return truel  //Match
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值