可比较的类和二叉搜索树
Comparable Class and Binary Search Tree
我需要创建一个抽象的'可比'类。从此类继承的任何类都将实现 compare_to 方法。
/* returns 1 if this class > rhs, 0 if equal, -1 if this class < rhs */
int compare_to(const Comparable& rhs);
创建一个二叉搜索树类,该类存储"可比较"对象而不是整数。
我遇到的问题是理解二叉搜索树类的外观以及我们如何在其中存储可比较的对象。
我们可以使用模板。
不要这样做,不要做任何通用界面。这有很多缺点。如果从 IComparable 派生的两个类不能相互比较 - 如 Int 和 String,该怎么办?
你说你可以使用模板。使用它们 - 并提供比较器作为第二个模板参数:
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;
我相信
你必须为二叉搜索树创建类模板。类模板将如下所示
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
类型对象的比较方法。
相关文章:
- 有根的二进制搜索树.保留与其父级的链接
- 正在尝试重载二进制搜索树分配运算符
- 使用C++创建特殊的二叉搜索树
- 在递归二叉搜索树中搜索
- 在二叉搜索树中插入时出现分段错误
- C++二叉搜索树模板从函数返回节点
- 我可以在没有堆栈的情况下在二叉搜索树中实现迭代器吗?
- 在二叉搜索树C++中计算平均值
- 在字符串的二叉搜索树中搜索子字符串 - C++
- 在二叉搜索树中插入新元素
- 如何打印在二叉搜索树中找到的数据?
- 查找存储在二叉搜索树的所有非叶子中的数据总和?(返回整数的独立递归函数
- 这是一个二叉搜索树吗?黑客排名问题
- 二叉搜索树 - 实现"search"函数
- 将字符串与二叉搜索树中的对象进行比较
- 如何计算二叉搜索树中的比较
- 可比较的类和二叉搜索树
- 我该如何计算在二进制搜索树中进行的比较
- 二进制搜索树-C++-表达式必须是可修改的左值
- C++二叉搜索树比较节点的数据并删除重复项