STL中map和set底层的红黑树实现

本文介绍了一种使用红黑树实现set和map的方法。通过定义通用模板参数,可以根据不同的需求选择实现set或map。文章详细展示了红黑树迭代器的前后置操作,并提供了具体的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们都知道map和set的实现是依赖红黑树的
怎样写红黑树可以让map和set都可以使用呢?
在这里我们定义了一个模版参数,如果它是key那么它就是set,如果它是map,那么它就是map;

我们分析一下,红黑树迭代器的前置++
到当前结点,就说明了它的左子树和自己都已经访问过了
1,当前位置,若右树不为空,则访问右树的最左结点
2,当前位置,若右树为空,则找祖先中孩子不是他的右
若右访问完,那么父亲这棵树也就访问完了
前置–的算法思想和++是近似的。

比较大小时,set直接比较它的key,而map是比较pair中的key
所以我们要新增加一个模版参数KeyOfValue
下面RBTree的代码实现:

#include<iostream>
#include<assert.h>
using namespace std;

enum Color
{
    RED,
    BLACK
};

template<class ValueType>
struct RBTreeNode
{
    RBTreeNode<ValueType>* _left;
    RBTreeNode<ValueType>* _right;
    RBTreeNode<ValueType>* _parent;

    ValueType _valueField;
    Color _col;

    RBTreeNode(const ValueType& v)
        :_left(NULL)
        , _right(NULL)
        , _parent(NULL)
        , _valueField(v)
        , _col(RED)
    {}
};

template<class ValueType>
class RBTreeIterator
{
public:
    typedef RBTreeNode<ValueType> Node;
    typedef RBTreeIterator<ValueType> Self;

    Node* _node;

    RBTreeIterator(Node* node)
        :_node(node)
    {}

    ValueType& operator*()
    {
        return _node->_valueField;
    }

    ValueType* operator->()
    {
        //return &_node->_valueField;
        return &(operator*());
    }

    Self& operator++()
    {
        if (_node->_right)
        {
            Node* leftLeft = _node->_right;
            while (leftLeft->_left)
            {
                leftLeft = leftLeft->_left;
            }
            _node = leftLeft;
        }
        else
        {
            Node* cur = _node;
            Node* parent = cur->_parent;
            while (parent&&cur == parent->_right)
            {
                cur = parent;
                parent = cur->_parent;
            }
            _node = parent;
        }
        return *this;
    }

    Self operator++(int)
    {
        Self tmp(*this);
        ++(*this);
        return tmp;
    }

    Self& operator--()
    {
        if (_node->_left)
        {
            Node* rightRight = _node->_left;
            while (rightRight->_right)
            {
                rightRight = rightRight->_right;
            }
            _node = rightRight;
        }
        else
        {
            Node* cur = _node;
            Node* parent = cur->_parent;
            while (parent&&cur == parent->_left)
            {
                cur = parent;
                parent = cur->_parent;
            }
            _node = parent;
        }
        return *this;
    }

    Self operator--(int)
    {
        Self tmp(*this);
        --(*this);
        return tmp;
    }

    bool operator==(const Self& s)
    {
        return _node == s._node;
    }
    bool operator!=(const Self& s)
    {
        return _node != s._node;
    }
};
template<class K, class V, class KeyOfValue>
class RBTree
{
public:
    typedef V ValueType;
    typedef RBTreeNode<ValueType> Node;
    typedef RBTreeIterator<ValueType> Iterator;

    RBTree()
        :_root(NULL)
    {}

    Iterator Begin()
    {
        Node* left = _root;
        while (left&&left->_left)
        {
            left = left->_left;
        }
        return Iterator(left);

    }
    Iterator End()
    {
        return Iterator(NULL);
    }

    Iterator RBegin()
    {
        Node* right = _root;
        while (right && right->_right)
        {
            right = right->_right;
        }

        return right;
    }

    Iterator REnd()
    {
        return NULL;
    }

    pair<Iterator, bool> Insert(const ValueType& v)
    {
        if (_root == NULL)
        {
            _root = new Node(v);
            _root->_col = BLACK;

            return make_pair(Iterator(_root), true);
        }

        KeyOfValue keyOfValue;
        Node* parent = NULL;
        Node* cur = _root;
        while (cur)
        {
            if (keyOfValue(cur->_valueField) > keyOfValue(v))
            {
                parent = cur;
                cur = cur->_left;
            }
            else if (keyOfValue(cur->_valueField) < keyOfValue(v))
            {
                parent = cur;
                cur = cur->_right;

            }
            else
            {
                return make_pair(Iterator(cur), false);
            }
        }
        //找到插入位置
        cur = new Node(v);
        Node* newNode = cur;//记录cur,后面的操作会改变cur

        if (keyOfValue(parent->_valueField) < keyOfValue(v))
        {
            parent->_right = cur;
            cur->_parent = parent;
        }
        else
        {
            parent->_left = cur;
            cur->_parent = parent;
        }
        while (parent&&parent->_col == RED)
        {
            Node* grandparent = parent->_parent;
            if (parent == grandparent->_left)
            {
                Node* uncle = grandparent->_right;
                if (uncle && uncle->_col == RED)
                {
                    parent->_col = BLACK;
                    uncle->_col = BLACK;
                    grandparent->_col = RED;

                    cur = grandparent;
                    parent = cur->_parent;
                }
                else //uncle不存在,或uncle为黑色
                {
                    if (cur == parent->_right)
                    {
                        RotateL(parent);
                        swap(parent, cur);
                    }

                    RotateR(grandparent);
                    parent->_col = BLACK;
                    grandparent->_col = RED;

                    break;
                }
            }
            else//parent == grandparent->_right
            {
                Node* uncle = grandparent->_left;
                if (uncle&&uncle->_col == RED)
                {
                    parent->_col = BLACK;
                    uncle->_col = BLACK;
                    grandparent->_col = RED;

                }
                else//uncle不存在或者为黑色
                {
                    if (cur == parent->_left)
                    {
                        RotateR(parent);
                        swap(parent, cur);
                    }

                    RotateL(grandparent);
                    parent->_col = BLACK;
                    grandparent->_col = RED;

                    //break;
                }

            }
        }

        _root->_col = BLACK;

        return make_pair(Iterator(newNode), true);
    }

    Iterator Find(const K& key)
    {
        KeyOfValue keyOfValue;
        Node* cur = _root;
        while (cur)
        {
            if (keyOfValue(cur->_valueField) > key)
            {
                cur = cur->_left;
            }
            else if ((keyOfValue(cur->_valueField)) < key)
            {
                cur = cur->_right;
            }
            else
            {
                return Iterator(cur);
            }
        }
        return Iterator(NULL);
    }

    void RotateL(Node* parent)
    {
        Node* subR = parent->_right;
        Node* subRL = subR->_left;

        parent->_right = subRL;

        if (subRL)
        {
            subRL->_parent = parent;

        }
        subR->_left = parent;
        Node* parentparent = parent->_parent;
        parent->_parent = subR;
        if (parentparent == NULL)
        {
            _root = subR;
            subR->_parent = NULL;
        }
        else
        {
            if (parent == parentparent->_left)
            {
                parentparent->_left = subR;
                subR->_parent = parentparent;
            }
            else
            {
                parentparent->_right = subR;
                subR->_parent = parentparent;
            }
        }

    }
    void RotateR(Node* parent)
    {
        Node* subL = parent->_left;
        Node* subLR = subL->_right;

        parent->_left = subLR;

        if (subLR)
        {
            subLR->_parent = parent;
        }
        subL->_right = parent;
        Node* parentparent = parent->_parent;
        parent->_parent = subL;

        if (parentparent == NULL)
        {
            _root = subL;
            _root->_parent = NULL;
        }
        else
        {
            if (parent == parentparent->_left)
            {
                parentparent->_left = subL;
                subL->_parent = parentparent;
            }
            else
            {
                parentparent->_right = subL;
                subL->_parent = parentparent;
            }
        }
    }


private:
    Node* _root;
};

set代码实现:

#include<iostream>
#include<assert.h>
#include"RBTree.h"
using namespace std;


template<class K>
class Set
{
public:
    Set()
        :_s(NULL)
    {}

    struct KeyOfValue//在类外需要在定义模版参数
    {
        K operator()(const K& key)
        {
            return key;
        }
    };

    typedef typename RBTree<K, K, KeyOfValue>::Iterator Iterator;

    Iterator Begin()
    {
        return _s.Begin();
    }

    Iterator End()
    {
        return _s. End();
    }

    Iterator RBegin()
    {
        return _s.RBegin();
    }

    Iterator REnd()
    {
        return _s.REnd();
    }

    Iterator Find()
    {
        return _s.Find();
    }

    pair<Iterator,bool> Insert(const K& key)
    {
        return _s.Insert(key);
    }
private:
    RBTree<K, K, KeyOfValue> _s;
};

void testset()
{
    Set<int> s;
    s.Insert(12);
    s.Insert(31);
    s.Insert(45);
    Set<int>::Iterator it = s.Begin();
    while (it != s.End())
    {
        cout << *it << " ";
        ++it;
    }
    cout << endl;
}

map代码的实现:

#pragma once
#include "RBTree.h"

template<class K, class V>
struct MapKeyOfValue
{
    K operator()(const V& kv)
    {
        return kv.first;
    }
};

template<class K, class V, class KeyOfValue = MapKeyOfValue<K, pair<K, V>>>
class Map
{
public:

    typedef typename RBTree<K, pair<K, V>, KeyOfValue>::Iterator Iterator;

    Iterator Begin()
    {
        return t.Begin();
    }

    Iterator End()
    {
        return t.End();
    }

    bool Insert(const pair<K, V>& value)
    {
        return t.Insert(value);
    }

    V& operator[](const K& key)
    {
        // (*((this->insert(make_pair(k,mapped_type()))).first)).second
        pair<Iterator, bool> ret = t.Insert(make_pair(key, V()));
        return ret.first->second;
    }

protected:
    RBTree<K, pair<K, V>, KeyOfValue> t;
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值