B+树节点实现

B+ Tree node implementation

本文关键字:实现 树节点      更新时间:2023-10-16

Im为类实现一个B+树。节点目前是这样实现的:

class Node {
    public:
        E* keys[order*2];
        Node *children[order*2+1];
        int size;
        Node(){ 
            size = 0;
        }
        bool empty() {
            return size == 0;
        }
        bool isLeafNode() {
            return false;
        }
};
class LeafNode : public Node {
    public:
        E* data[order*2+1];
        bool isLeafNode() {
            return true;
        }
};

当我想向叶节点添加元素时(通过访问LeafNode->data(,我会得到

 error: request for member ‘data’ in ‘left<int>’, which is of non-class type ‘BTree<int>::LeafNode*()’

我想发生这种情况是因为编译器不知道我访问的节点是内部节点还是叶节点,尽管我首先使用isLeafNode((进行检查。我无法将这两个类合并为一个类,因为叶节点比内部节点需要多一个Bucket来处理数据。

我意识到这是一个设计问题,但我是否缺少一些解决这个问题的琐碎方法?我对C++还相当陌生。

对于这样的事情,您确实应该使用虚拟方法。您可以更改isLeafNode()查询以返回指向叶节点的指针(如果是(,否则返回NULL。

class LeafNode; // forward declare
class Node {
//...
public:
    virtual ~Node () {}
    virtual LeafNode * isLeafNode () { return 0; }
    //...
};
class LeafNode : public Node {
//...
public:
    LeafNode * isLeafNode () { return this; }
    //...
};

然后,如果data实际上是LeafNode,则可以从Node使用此方法来访问它。

错误消息

error: request for member ‘data’ in ‘left<int>’, which is of non-class type  ‘BTree<int>::LeafNode*()’

而此表单的其他错误通常意味着您正试图使用.访问struct的字段,而您应该使用->。例如,如果你有

LeafNode* ptr = /* ... */;
ptr.data[0] = /* ... */;

您将在第二行得到一个错误,因为您使用的是.而不是->

试着看看这是否是指示线上的错误,如果是,请将点改为箭头。

希望这能有所帮助!