C 语言

关注公众号 jb51net

关闭
首页 > 软件编程 > C 语言 > 封装红黑树mymap和myset

C++封装红黑树实现mymap和myset完整代码

作者:凤年徐

红黑树作为一种自平衡的二叉搜索树,是C++标准库中map和set容器的底层实现,下面这篇文章主要介绍了C++封装红黑树实现mymap和myset的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下

一、源码及框架分析

在 SGI-STL 30 版本中,mapset 的实现巧妙地复用了同一棵红黑树(rb_tree)。其核心代码主要位于 stl_tree.hstl_map.hstl_set.h 中。

1.1 框架核心代码

以下是 setmap 的简化定义:

// stl_set.h
template <class Key, class Compare = less<Key>, class Alloc = alloc>
class set {
public:
    typedef Key key_type;
    typedef Key value_type;
private:
    typedef rb_tree<key_type, value_type,
                    identity<value_type>, key_compare, Alloc> rep_type;
    rep_type t; // 底层红黑树
};
// stl_map.h
template <class Key, class T, class Compare = less<Key>, class Alloc = alloc>
class map {
public:
    typedef Key key_type;
    typedef T mapped_type;
    typedef pair<const Key, T> value_type;
private:
    typedef rb_tree<key_type, value_type,
                    select1st<value_type>, key_compare, Alloc> rep_type;
    rep_type t; // 底层红黑树
};

1.2 红黑树的泛型设计

rb_tree 通过模板参数实现泛型,使其既能用于 set(存储 Key),也能用于 map(存储 pair<const Key, T>)。其结点定义如下:

template <class Value>
struct __rb_tree_node : public __rb_tree_node_base {
    typedef __rb_tree_node<Value>* link_type;
    Value value_field; // 存储的实际数据
};

rb_tree 的模板参数:

template <class Key, class Value, class KeyOfValue, class Compare, class Alloc = alloc>
class rb_tree {
    // ...
};

1.3 为何需要两个模板参数Key和Value?

set 的两个模板参数相同,map 则不同。这是因为:

mapValuepair<const Key, T>,但查找时只需传入 Key 类型的值,因此两个模板参数缺一不可。

注:源码中命名风格略有混乱,set 使用 Keymap 使用 KeyTrb_tree 又使用 KeyValue,但设计思路清晰。

二、模拟实现 map 和 set

接下来,我们将基于自己实现的红黑树,封装出 mapset

2.1 实现红黑树框架,支持插入

我们首先实现一个红黑树 RBTree,它通过 KeyOfT 仿函数提取键值进行比较。

RBTree.h

enum Colour { RED, BLACK };
template<class T>
struct RBTreeNode {
    T _data;
    RBTreeNode<T>* _left;
    RBTreeNode<T>* _right;
    RBTreeNode<T>* _parent;
    Colour _col;
    RBTreeNode(const T& data)
        : _data(data), _left(nullptr), _right(nullptr), _parent(nullptr), _col(RED) {}
};
template<class K, class T, class KeyOfT>
class RBTree {
    typedef RBTreeNode<T> Node;
public:
    bool Insert(const T& data) {
        if (_root == nullptr) {
            _root = new Node(data);
            _root->_col = BLACK;
            return true;
        }
        KeyOfT kot;
        Node* parent = nullptr;
        Node* cur = _root;
        while (cur) {
            if (kot(cur->_data) < kot(data)) {
                parent = cur;
                cur = cur->_right;
            } else if (kot(cur->_data) > kot(data)) {
                parent = cur;
                cur = cur->_left;
            } else {
                return false; // 键已存在
            }
        }
        cur = new Node(data);
        Node* newnode = cur;
        cur->_col = RED;
        if (kot(parent->_data) < kot(data))
            parent->_right = cur;
        else
            parent->_left = cur;
        cur->_parent = parent;
        // 后续平衡处理(旋转、变色)省略,完整代码见文末
        return true;
    }
private:
    Node* _root = nullptr;
};

Mymap.h

namespace bit {
    template<class K, class V>
    class map {
        struct MapKeyOfT {
            const K& operator()(const pair<K, V>& kv) {
                return kv.first;
            }
        };
    public:
        bool insert(const pair<K, V>& kv) {
            return _t.Insert(kv);
        }
    private:
        RBTree<K, pair<K, V>, MapKeyOfT> _t;
    };
}

Myset.h

namespace bit {
    template<class K>
    class set {
        struct SetKeyOfT {
            const K& operator()(const K& key) {
                return key;
            }
        };
    public:
        bool insert(const K& key) {
            return _t.Insert(key);
        }
    private:
        RBTree<K, K, SetKeyOfT> _t;
    };
}

2.2 支持迭代器

迭代器的核心是 operator++operator--,实现中序遍历的步进逻辑。

迭代器实现思路

迭代器代码

template<class T, class Ref, class Ptr>
struct RBTreeIterator {
    typedef RBTreeNode<T> Node;
    typedef RBTreeIterator<T, Ref, Ptr> Self;
    Node* _node;
    Node* _root; // 用于处理 end() 的情况
    RBTreeIterator(Node* node, Node* root) : _node(node), _root(root) {}
    Ref operator*() { return _node->_data; }
    Ptr operator->() { return &_node->_data; }
    Self& operator++() {
        if (_node->_right) {
            Node* leftMost = _node->_right;
            while (leftMost->_left) leftMost = leftMost->_left;
            _node = leftMost;
        } else {
            Node* cur = _node;
            Node* parent = cur->_parent;
            while (parent && cur == parent->_right) {
                cur = parent;
                parent = cur->_parent;
            }
            _node = parent;
        }
        return *this;
    }
    Self& operator--() {
        if (_node == nullptr) { // 处理 --end()
            Node* rightMost = _root;
            while (rightMost && rightMost->_right) rightMost = rightMost->_right;
            _node = rightMost;
        } else if (_node->_left) {
            Node* rightMost = _node->_left;
            while (rightMost->_right) rightMost = rightMost->_right;
            _node = rightMost;
        } else {
            Node* cur = _node;
            Node* parent = cur->_parent;
            while (parent && cur == parent->_left) {
                cur = parent;
                parent = cur->_parent;
            }
            _node = parent;
        }
        return *this;
    }
    bool operator!=(const Self& s) const { return _node != s._node; }
    bool operator==(const Self& s) const { return _node == s._node; }
};

在 RBTree 中集成迭代器

template<class K, class T, class KeyOfT>
class RBTree {
public:
    typedef RBTreeIterator<T, T&, T*> Iterator;
    typedef RBTreeIterator<T, const T&, const T*> ConstIterator;
    Iterator Begin() {
        Node* leftMost = _root;
        while (leftMost && leftMost->_left) leftMost = leftMost->_left;
        return Iterator(leftMost, _root);
    }
    Iterator End() { return Iterator(nullptr, _root); }
    // 同理实现 ConstIterator
private:
    Node* _root = nullptr;
};

2.3 支持operator[]

map[] 需要借助 insert 的返回值实现。因此,RBTree::Insert 需返回 pair<Iterator, bool>

pair<Iterator, bool> Insert(const T& data) {
    // 插入逻辑,返回插入位置的迭代器及是否成功
}

然后在 map 中:

V& operator[](const K& key) {
    pair<iterator, bool> ret = insert(make_pair(key, V()));
    return ret.first->second;
}

2.4 完整代码

最终版Myset.h

#include "RBTree.h"
namespace bit {
    template<class K>
    class set {
        struct SetKeyOfT {
            const K& operator()(const K& key) { return key; }
        };
    public:
        typedef typename RBTree<K, const K, SetKeyOfT>::Iterator iterator;
        typedef typename RBTree<K, const K, SetKeyOfT>::ConstIterator const_iterator;
        iterator begin() { return _t.Begin(); }
        iterator end() { return _t.End(); }
        const_iterator begin() const { return _t.Begin(); }
        const_iterator end() const { return _t.End(); }
        pair<iterator, bool> insert(const K& key) { return _t.Insert(key); }
        iterator find(const K& key) { return _t.Find(key); }
    private:
        RBTree<K, const K, SetKeyOfT> _t;
    };
}

最终版Mymap.h

#include "RBTree.h"
namespace bit {
    template<class K, class V>
    class map {
        struct MapKeyOfT {
            const K& operator()(const pair<K, V>& kv) { return kv.first; }
        };
    public:
        typedef typename RBTree<K, pair<const K, V>, MapKeyOfT>::Iterator iterator;
        typedef typename RBTree<K, pair<const K, V>, MapKeyOfT>::ConstIterator const_iterator;
        iterator begin() { return _t.Begin(); }
        iterator end() { return _t.End(); }
        const_iterator begin() const { return _t.Begin(); }
        const_iterator end() const { return _t.End(); }
        pair<iterator, bool> insert(const pair<K, V>& kv) { return _t.Insert(kv); }
        iterator find(const K& key) { return _t.Find(key); }
        V& operator[](const K& key) {
            pair<iterator, bool> ret = insert(make_pair(key, V()));
            return ret.first->second;
        }
    private:
        RBTree<K, pair<const K, V>, MapKeyOfT> _t;
    };
}

最终版RBTree.h

完整代码请参考文末总结部分,或结合上述片段整合。核心包括:

三、总结

通过封装红黑树实现 mapset,我们深入理解了 STL 中容器复用的设计思想:

  1. 泛型设计:红黑树通过 Value 模板参数决定存储内容,通过 KeyOfT 仿函数提取键值进行比较。
  2. 迭代器实现:中序遍历的步进逻辑是迭代器实现的核心,需同时处理左右子树与祖先关系。
  3. map[] 实现:依赖于 insert 的返回值,简洁高效。
  4. 权限控制set 的迭代器不允许修改键值,通过将 Value 模板参数设为 const K 实现;map 则通过 pair<const K, V> 保护键不被修改。

这种复用方式不仅减少了代码量,还体现了面向对象与泛型编程的强大结合。

到此这篇关于C++封装红黑树实现mymap和myset完整代码的文章就介绍到这了,更多相关封装红黑树mymap和myset内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文