使用函數對象(侯捷先生譯爲僞函數)實現二叉查找樹

以前看過《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
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章