可比类和二叉搜索树

时间:2012-10-11 19:24:56

标签: c++ binary-search-tree

我需要创建一个抽象的'Comparable'类。从该类继承的任何类都将实现compare_to方法。

/* returns 1 if this class > rhs, 0 if equal, -1 if this class < rhs */    
int compare_to(const Comparable& rhs);

创建一个Binary Search Tree类,它存储“Comparable”对象而不是整数。

我遇到的问题是了解Binary Search Tree类的外观以及我们如何在其中存储Comparable对象。

我们可以使用模板。

2 个答案:

答案 0 :(得分:1)

不要这样做,不要做任何通用界面。这有许多缺点。如果从IComparable派生的两个类不能相互比较 - 比如Int和String会怎样?

你说你可以使用模板。使用它们 - 并提供Comparator作为第二个模板参数:

template <class T, class Comparator>
class BSTree  {
public:
   bool present(const T& value)
   {
       int res = comparator(value, root->value);
       switch(res) {
         case 0: return true;
         case -1: return find(root->left, value);
         case 1: return find(root->right, value);
       }
   }
private:
  struct Node {
  ...
  };
  Node* root;
  Comparator comparator;
};

典型的比较器是:

template <class T>
class RawComparator {
public:
    int operator()(const T& l, const T& r) 
    {
       if (l < r) return -1;
       else if (l > r) return 1;
       else return 0;
    }

};

你的二进制搜索树为int:

typedef BSTree<int, RawComparator<int>> BSTreeInt;

答案 1 :(得分:0)

我相信您必须为二叉搜索树创建类模板。 类模板看起来像

template <typename Comparable>
class BSTNode
{
public:
BSTNode const Comparable & theElement = Comparable( ),BSTNode *lt = NULL, BSTNode *rt = NULL);
int size( BSTNode *t ) ;
int height( BSTNode *t);
void printPostorder( ) ; 
void printInOrder( ) ; 
void printPreOrder( ) ;
bool operator<(const Comparable&,const Comparable &); 
BSTNode *duplicate() ;


public:

Comparable element;
BSTNode *left;
BSTNode *right;

};

然后您可以重载operator<以添加Comparable类型对象的比较方法。

相关问题