我需要创建一个抽象的“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/