我有一个类Tree
我想将其扩充为更专业的数据结构,例如 Order_tree
和 Interval_tree
.这些扩充需要添加到 Node
,例如大小信息,以及对某些算法的微小改动。
我想知道在性能、可读性和可维护性方面用 C++ 实现扩充的最佳方法。不应以多态方式使用树。到目前为止我尝试的是公开继承 Tree
,然后重载基本方法。 (很抱歉我是面向对象编程的初学者)
template <typename T>
class Tree {
protected:
enum class Color : char {BLACK = 0, RED = 1};
struct Node {
T key;
Node *parent, *left, *right;
Color color;
Node() : color{Color::BLACK} {} // sentinel construction
Node(T val, Color col = Color::RED) : key{val}, parent{nil}, left{nil}, right{nil}, color{col} {}
};
using NP = typename Tree::Node*;
NP root {nil};
// nil sentinel
static NP nil;
// core utility algorithms...
};
template <typename T>
typename Tree<T>::NP Tree<T>::nil {new Node{}};
订单树
template <typename T>
class Order_tree : public Tree<T> {
using Color = typename Tree<T>::Color;
using Tree<T>::Tree; // inherit constructors
struct Order_node {
T key;
Order_node *parent, *left, *right;
size_t size; // # of descendent nodes including itself = left->size + right->size + 1
Color color;
Order_node() : size{0}, color{Color::BLACK} {} // sentinel construction
Order_node(T val, Color col = Color::RED) : key{val}, parent{nil}, left{nil}, right{nil}, size{1}, color{col} {}
};
using NP = typename Order_tree::Order_node*;
NP root {nil};
static NP nil;
// overloading on only the methods that need changing
};
template <typename T>
typename Order_tree<T>::NP Order_tree<T>::nil {new Order_node{}};
但是,这并不正常,因为现在我有 2 个根和 2 个 nils,所有基本方法都在基本根上工作,并且使用 Tree<T>::NP
。而不是 Order_tree::NP
所以 Order_node
不能使用的大小属性。
一种方法是复制粘贴代码,这是非常难以维护的。我认为另一种方法是在 T 和 NP 上模板化树,这样 Order_tree
是一个别名 using Order_tree = Tree<Order_node>
并在节点上专门化树。
最佳答案
如果您真的对拥有“所有树的通用树”感兴趣,那么问题似乎不在树中,而在 Node 中。您需要节点的一些特殊情况,那么为什么不将它们也泛化呢?例如:
template <typename T>
class Tree {
protected:
struct BaseNode {
//all code you really can generalize here
};
struct Node : public BaseNode {
//You need Node here only if you want your base Tree class to be ready to use.
//If you want to use only its derives such as Order_tree,
//you create special nodes kinds only there
};
// core utility algorithms...
BaseNode * root; //Only one root node, there is no need in duplication!
//You can instantiate it as root = new OrderTreeNode or root = new SpecialTreeNode in any derives.
};
但是调用 Node 虚函数的代价是相当大的。因此,您需要清楚地了解 - 您是需要泛化而不是重复代码,还是需要性能。
关于c++ - 在不浪费内存的情况下扩充数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27478387/