2015-12-21 96 views
-1

我正在閱讀其他人的代碼,這部分讓我困惑。任何人都可以向我解釋*this在這裏指什麼,這條線(for_each(node->items.begin(), node->items.end(), *this);)在做什麼?這段代碼來自搜索R/R *樹中的元素。我想在這裏,我們應該提供一個函子for_each(begin,end,functor),但我不知道*this(這在我看來是「node->items」矢量的元素)實際上會做什麼。C++「this」指針在for_each

// this functor recursively walks the tree 
     template <typename Acceptor, typename Visitor> 
     struct QueryFunctor : std::unary_function< const BoundedItem, void > { 
       const Acceptor &accept; 
       Visitor &visitor; 

       explicit QueryFunctor(const Acceptor &a, Visitor &v) : accept(a), visitor(v) {} 

       void operator()(BoundedItem * item) 
       { 
         Node * node = static_cast<Node*>(item); 

         if (visitor.ContinueVisiting && accept(node)) 
         { 
           if (node->hasLeaves) 
             for_each(node->items.begin(), node->items.end(), VisitFunctor<Acceptor, Visitor>(accept, visitor)); 
           else 
             for_each(node->items.begin(), node->items.end(), *this); 
         } 
       } 
     }; 
+0

'this'是一個指向特定方法被調用的對象的指針。 –

+3

'for_each'是標準庫的一部分,因此您可以輕鬆地在線搜索它。例如[這裏](http://en.cppreference.com/w/cpp/algorithm/for_each) –

+0

我絕對知道for_each @FabioTurati – daydayup

回答

1

R* tree是更好的查詢性能(但略高建設成本)R型樹。 R樹是一個包含目錄(非結束節點)和葉子(結束節點)的數據結構。節點的成員bool hasLeaves指示節點是否包含目錄(hasLeavesfalse)或葉子(hasLeavestrue)。目錄只是遞歸遍歷的,但葉子是我們感興趣的。

當代碼調用for_each(..., *this)時,它會爲給定範圍內的每個項目調用QueryFunctor::operator()(BoundedItem * item)for_each可以同時使用一個函數或者一個運算符(),並且在這種情況下它是operator()。給定範圍的元素實際上是Node*類型,但Node是從BoundedItem派生的,所以參數類型匹配。這在您使用static_cast行提供的代碼中可見,但爲了更好地理解,我閱讀了完整的代碼here