1. 程式人生 > >傻瓜教程:手把手教你解決多個應用例項(附程式碼、手繪圖)

傻瓜教程:手把手教你解決多個應用例項(附程式碼、手繪圖)

// Reminder: this is pseudocode, no bother with "const&", "std::" or others
// forgive me C++ fellows

template <typename BlaBla>
class BST
{
public:
 // other code ...
 
 vector<BlaBla*> ReverseInOrderProduceVector(int offset, int limit)
 {
   vector<BlaBla*> result;
   result.reserve(limit);
   // passing result vector by reference
   // and passing offset and limit
   ReverseInOrderProduceVectorHelper_(root_, result, offset, limit);
   return result;
 }
 
protected:
 // takes a reference to vector
 // skips 'offset' nodes and inserts up to 'limit' nodes
 void ReverseInOrderProduceVectorHelper_(BSTNode* node, vector<BlaBla*>& destination, int offset, int limit)
 {
   if (!node) return;
   if (limit == 0) return;
   --offset; // skipping current element
   ReverseInOrderProduceVectorHelper_(node->right, destination, offset, limit);
   if (offset <= 0) { // if skipped enough, insert
     destination.push_back(node->value);
     --limit; // keep the count of insertions
   }
   ReverseInOrderProduceVectorHelper_(node->left, destination, offset, limit);
 }
 
private:
 BSTNode* root_;
};

// ... other possibly useful code

// this is a pseudocode, that's why I didn't bother with "const&"'s and "std::"'s
// though it could have look better, forgive me C++ fellows

vector<Item*> GetItemsByKeywordInSortedOrder(string keyword, offset, limit) // pagination using offset and limit
{
 // assuming IndexTable is a big hashtable mapping keywords to Item BSTs
 BST<Item*> items = IndexTable[keyword];
 
 // suppose BST has a function InOrderProduceVector(), which creates a vector and
 // inserts into it items fetched via reverse in-order traversing the tree
 // to get items in descending order (starting from the highest rated item)
 vector<Item*> sorted_result = items.ReverseInOrderProduceVector(offset, limit);
 return sorted_result;
}