c++ - 可比较类和二叉搜索树

标签 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);

创建一个存储“可比较”对象而不是整数的二叉搜索树类。

我遇到的问题是理解二叉搜索树类的外观以及我们如何在其中存储 Comparable 对象。

我们可以使用模板。

最佳答案

不要这样做,不要做任何通用的接口(interface)。这有很多缺点。如果派生自 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;

关于c++ - 可比较类和二叉搜索树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12847025/

相关文章:

c++ - 从静态库函数访问文本数据文件

java - 将字符串数组传输到二叉树

java - 在 java 中扩展与实现 Comparable

c++ - 二叉搜索树赋值运算符

c - 二叉搜索树按顺序打印

python - Inorder树走不工作

c++ - 从堆和内存泄漏中删除 C++ 数组

c++ - 在 C# 中连接到 Websphere MQ 有效,但在 C++ 中失败,代码为 2058 (MQRC_Q_MGR_NAME_ERROR)

c++ - 模板类析构函数

c++ - 用于创建混合类的 MPL 工厂方法