将平衡BST扩展为C ++ STL Map

时间:2014-09-01 13:41:58

标签: c++ c++11 map stl

为了练习,我实现了一个平衡的二叉搜索树(红黑树)。这是我到目前为止实现的底层节点和方法的数据结构的标题:

#ifndef BST_H
#define BST_H
template <typename T>
class treeNode {
public:
    treeNode *left;
    treeNode *right;
    T key;
    treeNode(T key)
        : key(key)
        , left(nullptr)
        , right(nullptr) {
    }
};

template <typename T>
class BST {
public:
    BST() {
        root = nullptr;
        nodes = 0;
    }

    BST(BST const& rhs);

    BST& operator = (BST rhs) {
        this->swap(rhs);
    }

    BST& operator = (BST&& rhs) {
        this->swap(rhs);
    }

    ~BST() {
        clear(root);
    }

    void swap(BST& other) {
        std::swap(root, other.root);
        std::swap(nodes, other.nodes);
    }

    void clear(treeNode<T>* node) {
        if(node) {
            if(node->left) clear(node->left);
            if(node->right) clear(node->right);
            delete node;
        }
    }

    bool isEmpty() const {
        return root == nullptr;
    }
    void inorder(treeNode<T>*);
    void traverseInorder();

    void preorder(treeNode<T>*);
    void traversePreorder();

    void postorder(treeNode<T>*);
    void traversePostorder();

    void insert(T const& );

    void remove(T const& );

    treeNode<T>* search(const T &);

    treeNode<T>* minHelper(treeNode<T>*);
    treeNode<T>* min();

    treeNode<T>* maxHelper(treeNode<T>*);
    treeNode<T>* max();

    size_t size() const;

    void sort();
    treeNode<T>* inOrderSuccessor(treeNode<T>*);
    bool isBST(treeNode<T>*) const;
    bool isBST() const;

private:
    treeNode<T> *root;
    size_t nodes;
};
#endif

我打算实现C ++ STL map(我已经使用Hashtable实现了STL unordered_map,其基础数据结构是Red-Black Tree AFAIK。如何将树扩展为键值泛型类型映射?

不需要任何类型的源代码。一些直觉就足够了。谢谢:))

1 个答案:

答案 0 :(得分:1)

凭直觉:T可能是pair<const key_type,mapped_type>。我假设您目前使用node.key < another_node.key进行比较。这是行不通的,因为地图应仅使用该对的第一部分。您可以将Compare仿函数作为模板参数(以类似于您map类的方式)添加到树中,以使其对实现stl兼容映射有用。< / p>

您可以选择设计树,以便键和值类是分开的而不是组合的。以下是模板定义的示例代码:

template<class Key, class Value, class Comp=std::less<Key>>
class BST {
    Compare comp;
public:
    BST(const Comp& comp = Comp()): comp(comp)
//...

// usage
if(comp(node.key, another_node.key)) {
    // node is considered to be strictly before another_node

您可以将std::less用作树的其他用户的合理默认参数,但地图实现应转发为地图指定的比较器。

完全兼容的容器也应该支持自定义分配器并使其成为可能,内部树结构也必须如此。