• 一篇文章教会你利用红黑树实现map和set的封装


    请添加图片描述

    增加红黑树迭代器的代码

    首先我们可以复用上一节写出的红黑树代码,在原有基础上略作修改即可,这里我们只对map和set的迭代器功能实现做讲解,并不是完全实现,目的是为了深化学习map和set的底层原理

    1. map和set通用模板迭代器结构体定义

    template<class T, class Ref, class Ptr>
    struct __RBTreeIterator
    {
    	typedef RBTreeNode<T> Node;
    	typedef __RBTreeIterator<T, Ref, Ptr> Self;
    	Node* _node;
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    这段代码是为了同时实现 std::mapstd::set 的红黑树结构而定义的迭代器。在STL中, std::mapstd::set 都使用红黑树作为底层数据结构,但它们之间有一些差异,主要是在元素类型和键-值对之间。

    这个迭代器定义的目的是为了在不重复实现两种不同容器的迭代器的情况下,实现红黑树的通用迭代器,以便它可以同时用于 std::mapstd::set。让我解释一下为什么需要这样的定义:

    1. 通用性:这个迭代器的定义使得它可以适用于不同的数据类型 T,无论是 std::map 的键值对还是 std::set 的元素。这种通用性是非常有价值的,因为它允许你在不同的上下文中使用相同的迭代器。
    2. 代码重用:通过使用通用迭代器,STL可以避免在不同容器的迭代器之间重复编写相似的代码。这简化了STL的实现,减少了代码冗余。
    3. 一致性:STL追求一致性,希望用户可以像使用 std::map 的迭代器一样使用 std::set 的迭代器,或者反之。这使得STL更容易理解和使用。

    因此,这个迭代器定义的目的是为了实现通用性、代码重用和一致性,以提供更好的STL体验。在STL中,通常会看到这种类型的通用迭代器,以简化不同容器的实现。

    2. 迭代器拷贝构造

    __RBTreeIterator(Node* node)
        :_node(node)
    {}
    
    • 1
    • 2
    • 3

    这个构造函数是 __RBTreeIterator 迭代器的构造函数,它接受一个指向红黑树节点的指针作为参数,并将这个指针存储在 _node 成员变量中。

    构造函数的主要目的是初始化迭代器的状态,使其指向红黑树中的特定节点,从而使迭代器能够正确地遍历红黑树中的元素。在迭代器创建时,你可以传入一个节点指针,它将成为迭代器的起始位置。

    这种构造函数的设计允许你在创建迭代器时指定起始位置,以便从红黑树中的特定节点开始遍历。这在实现红黑树的迭代器时是常见的设计,因为你可能希望从根节点、某个特定节点或其他位置开始遍历树。

    3. 迭代器解引用重载

    Ref operator*()
    {
        return _node->_data;
    }
    
    • 1
    • 2
    • 3
    • 4

    这个 operator* 函数是迭代器的解引用操作符重载函数。它的目的是返回当前迭代器指向的元素的引用,允许你通过迭代器来访问元素的值。

    在这个具体的实现中,_node->_data 是红黑树节点中存储的元素值,它的类型是 Toperator* 函数返回的是这个元素值的引用,所以你可以通过迭代器来读取或修改当前节点的值。

    通常情况下,解引用操作符重载允许你以类似于指针的方式来访问迭代器指向的对象,这使得使用迭代器遍历容器时,你可以像访问容器元素一样来访问数据,增强了代码的可读性和易用性。在STL和C++中,迭代器的行为通常模仿指针的行为,因此你可以使用类似于指针的语法来操作元素。

    4. 迭代器箭头重载

    Ptr operator->()
    {
        return &_node->_data;
    }
    
    • 1
    • 2
    • 3
    • 4

    这个 operator-> 函数是迭代器的箭头成员访问操作符重载函数。它的目的是返回一个指向当前迭代器指向的元素的指针,以便你可以通过迭代器来访问元素的成员。

    在这个具体的实现中,_node->_data 是红黑树节点中存储的元素值,它的类型是 Toperator-> 函数返回的是一个指向这个元素值的指针,所以你可以使用箭头操作符来访问元素的成员变量或调用其成员函数。

    这个操作符的重载允许你以一种更直接的方式来访问迭代器指向的元素的成员。这在需要访问元素的内部数据或调用其方法时非常有用。

    例如,如果你的元素是一个自定义类的对象,你可以使用 -> 操作符来访问该对象的成员函数,就像你正在操作该对象一样。这提供了一种更自然、更便捷的访问元素的方式。

    5. 迭代器不等于重载

    bool operator!=(const Self& s) const
    {
        return _node != s._node;
    }
    
    • 1
    • 2
    • 3
    • 4

    这个 operator!= 函数是不等于运算符的重载函数。它的目的是比较当前迭代器和另一个迭代器 s 是否不相等。

    在这个具体的实现中,它比较了 _node 成员变量,如果两个迭代器的 _node 不相等,就返回 true,表示它们不相等;否则,返回 false,表示它们相等。

    这个操作符的重载使得你可以使用不等于运算符 != 来比较两个迭代器,以确定它们是否指向不同的位置。这对于循环遍历容器中的元素或判断迭代器是否达到容器末尾非常有用。通常情况下,你可以使用这个操作符来控制循环的终止条件。

    6. 迭代器判断相等重载

    bool operator==(const Self& s) const
    {
        return _node == s._node;
    }
    
    • 1
    • 2
    • 3
    • 4

    这个 operator== 函数是等于运算符的重载函数。它的目的是比较当前迭代器和另一个迭代器 s 是否相等。

    在这个具体的实现中,它比较了 _node 成员变量,如果两个迭代器的 _node 相等,就返回 true,表示它们相等;否则,返回 false,表示它们不相等。

    这个操作符的重载使得你可以使用等于运算符 == 来比较两个迭代器,以确定它们是否指向相同的位置。这对于检查迭代器是否相等以及判断是否达到容器末尾非常有用。通常情况下,你可以使用这个操作符来执行迭代器的相等性检查。

    7. 迭代器++重载

    Self& operator++()
    {
        if (_node->_right)
        {
            // 下一个就是右子树的最左节点
            Node* left = _node->_right;
            while (left->_left)
            {
                left = left->_left;
            }
    
            _node = left;
        }
        else
        {
            // 找祖先里面孩子不是祖先的右的那个
            Node* parent = _node->_parent;
            Node* cur = _node;
            while (parent && cur == parent->_right)
            {
                cur = cur->_parent;
                parent = parent->_parent;
            }
    
            _node = parent;
        }
    
        return *this;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    这个 operator++ 函数是前置自增运算符的重载函数,用于使迭代器指向下一个元素。在红黑树的迭代器中,它实现了迭代器的前进操作。

    这个函数的工作方式如下:

    1. 如果当前节点的右子树存在,迭代器将被移动到右子树的最左节点。这是因为在红黑树中,右子树的最左节点是比当前节点大的下一个节点。
    2. 如果当前节点没有右子树,迭代器将向上移动到祖先节点,直到找到一个祖先节点,它的右子节点不等于当前节点。这是因为在红黑树中,如果当前节点没有右子树,下一个节点要么是它的父节点,要么是它的某个祖先节点的左子节点。

    这个函数的目的是使迭代器指向下一个元素,以实现对红黑树的顺序遍历。在STL中,前置自增操作符通常用于移动迭代器到容器中的下一个元素。

    8. 迭代器–重载

    Self& operator--()
    {
        if (_node->_left)
        {
            // 下一个是左子树的最右节点
            Node* right = _node->_left;
            while (right->_right)
            {
                right = right->_right;
            }
    
            _node = right;
        }
        else
        {
            // 孩子不是父亲的左的那个祖先
            Node* parent = _node->_parent;
            Node* cur = _node;
            while (parent && cur == parent->_left)
            {
                cur = cur->_parent;
                parent = parent->_parent;
            }
    
            _node = parent;
        }
    
        return *this;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    这个 operator-- 函数是前置自减运算符的重载函数,用于使迭代器指向前一个元素。在红黑树的迭代器中,它实现了迭代器的后退操作。

    这个函数的工作方式与 operator++ 函数相似,但是方向相反:

    1. 如果当前节点的左子树存在,迭代器将被移动到左子树的最右节点。这是因为在红黑树中,左子树的最右节点是比当前节点小的上一个节点。
    2. 如果当前节点没有左子树,迭代器将向上移动到祖先节点,直到找到一个祖先节点,它的左子节点不等于当前节点。这是因为在红黑树中,如果当前节点没有左子树,上一个节点要么是它的父节点,要么是它的某个祖先节点的右子节点。

    这个函数的目的是使迭代器指向前一个元素,以实现对红黑树的逆序遍历。在STL中,前置自减操作符通常用于向前移动迭代器到容器中的前一个元素。

    修改红黑树结构体的成员及成员函数

    1. 修改红黑树结构体的成员定义

    template<class K, class T, class KeyOfT>
    struct RBTree
    {
    	typedef RBTreeNode<T> Node;
    public:
    	typedef __RBTreeIterator<T, T&, T*> iterator;
    private:
    	Node* _root = nullptr;
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    这里就是在红黑树结构体中将模板迭代器重命名为iterator

    2. 增加迭代器begin()和end()函数

    iterator begin()
    {
        Node* left = _root;
        while (left && left->_left)
        {
            left = left->_left;
        }
    
        return iterator(left);
    }
    
    iterator end()
    {
        return iterator(nullptr);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    这两个函数是用于创建红黑树迭代器的成员函数,通常用于在你的红黑树容器类中实现迭代器的 begin()end() 函数。

    1. begin() 函数用于返回指向红黑树中最小元素的迭代器。它通过从根节点开始,沿着左子树的路径一直向下移动,直到找到最左边的叶子节点,这个叶子节点就是最小的元素。然后它创建一个迭代器对象,将这个最小元素的节点指针传递给迭代器的构造函数,最后返回这个迭代器。
    2. end() 函数用于返回表示红黑树结束位置的迭代器。通常情况下,结束位置是一个空指针nullptr)。这个函数直接创建一个迭代器对象,将空指针传递给迭代器的构造函数,然后返回这个迭代器。

    这两个函数的实现使得你可以使用标准的迭代器语法来遍历红黑树中的元素。例如,你可以使用 begin() 获取指向第一个元素的迭代器,然后使用 end() 获取表示结束位置的迭代器,然后在循环中递增迭代器以遍历整个红黑树。这与STL容器的迭代器用法非常相似,使得在处理红黑树时更加方便和统一。

    3. 修改红黑树Insert函数

    pair<iterator, bool> Insert(const T& data)
    {
        KeyOfT kot;
    
        if (_root == nullptr)
        {
            _root = new Node(data);
            _root->_col = BLACK;
            return make_pair(iterator(_root), true);
        }
    
        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 make_pair(iterator(cur), 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;
    
        while (parent && parent->_col == RED)
        {
            Node* grandfater = parent->_parent;
            assert(grandfater);
            assert(grandfater->_col == BLACK);
            // 关键看叔叔
            if (parent == grandfater->_left)
            {
                Node* uncle = grandfater->_right;
                // 情况一 : uncle存在且为红,变色+继续往上处理
                if (uncle && uncle->_col == RED)
                {
                    parent->_col = uncle->_col = BLACK;
                    grandfater->_col = RED;
                    // 继续往上处理
                    cur = grandfater;
                    parent = cur->_parent;
                }// 情况二+三:uncle不存在 + 存在且为黑
                else
                {
                    // 情况二:右单旋+变色
                    if (cur == parent->_left)
                    {
                        RotateR(grandfater);
                        parent->_col = BLACK;
                        grandfater->_col = RED;
                    }
                    else
                    {
                        // 情况三:左右单旋+变色
                        //     g 
                        //   p   u
                        //     c
                        RotateL(parent);
                        RotateR(grandfater);
                        cur->_col = BLACK;
                        grandfater->_col = RED;
                    }
    
                    break;
                }
            }
            else // (parent == grandfater->_right)
            {
                Node* uncle = grandfater->_left;
                // 情况一
                if (uncle && uncle->_col == RED)
                {
                    parent->_col = uncle->_col = BLACK;
                    grandfater->_col = RED;
                    // 继续往上处理
                    cur = grandfater;
                    parent = cur->_parent;
                }
                else
                {
                    // 情况二:左单旋+变色
                    if (cur == parent->_right)
                    {
                        RotateL(grandfater);
                        parent->_col = BLACK;
                        grandfater->_col = RED;
                    }
                    else
                    {
                        // 情况三:右左单旋+变色
                        RotateR(parent);
                        RotateL(grandfater);
                        cur->_col = BLACK;
                        grandfater->_col = RED;
                    }
    
                    break;
                }
            }
    
        }
    
        _root->_col = BLACK;
        return make_pair(iterator(newnode), true);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127

    修改后它的返回值是一个 pair,其中包含一个迭代器和一个布尔值,用于表示插入是否成功。

    函数的主要步骤:

    1. 首先,检查红黑树是否为空,如果是空的,直接创建一个新节点 _root,将其染成黑色(根节点必须是黑色),然后返回一个包含指向新节点的迭代器和 truepair,表示插入成功。
    2. 如果红黑树不为空,则进入插入元素的循环。在循环中,首先通过 KeyOfT 对象 kot 来比较当前节点和要插入的数据,以确定应该将新节点插入到左子树还是右子树,或者是否已经存在相同的数据。如果找到相同的数据,函数会返回一个包含指向相同数据的迭代器和 falsepair,表示插入失败。
    3. 如果没有找到相同的数据,创建一个新节点 cur,将其染成红色,然后将其插入到适当的位置,这与标准的二叉搜索树插入操作相似。
    4. 插入完成后,函数进入红黑树修正循环,以确保满足红黑树的性质。在修正循环中,它首先检查当前节点的父节点和祖父节点的颜色,以确定需要采取哪种修正操作。具体的修正操作包括颜色变换和旋转操作,以保持红黑树的平衡性和性质。
    5. 最后,将根节点 _root 的颜色强制设置为黑色,以确保根节点始终为黑色。然后返回一个包含指向新插入节点的迭代器和 truepair,表示插入成功。

    这个函数的实现遵循红黑树的插入规则和修正策略,以保持红黑树的平衡和性质。它返回一个迭代器,可以用于访问新插入的元素,以及一个布尔值,指示插入是否成功。

    修改后红黑树全部代码

    #pragma once
    #include
    #include
    #include
    using namespace std;
    
    
    
    enum Colour
    {
    	RED,
    	BLACK
    };
    
    template<class T>
    struct RBTreeNode
    {
    	RBTreeNode<T>* _left;
    	RBTreeNode<T>* _right;
    	RBTreeNode<T>* _parent;
    
    	T _data;
    	Colour _col;
    
    	RBTreeNode(const T& data)
    		:_left(nullptr)
    		, _right(nullptr)
    		, _parent(nullptr)
    		, _data(data)
    	{}
    };
    
    template<class T, class Ref, class Ptr>
    struct __RBTreeIterator
    {
    	typedef RBTreeNode<T> Node;
    	typedef __RBTreeIterator<T, Ref, Ptr> Self;
    	Node* _node;
    
    	__RBTreeIterator(Node* node)
    		:_node(node)
    	{}
    
    	Ref operator*()
    	{
    		return _node->_data;
    	}
    
    	Ptr operator->()
    	{
    		return &_node->_data;
    	}
    
    	bool operator!=(const Self& s) const
    	{
    		return _node != s._node;
    	}
    
    	bool operator==(const Self& s) const
    	{
    		return _node == s._node;
    	}
    
    	Self& operator++()
    	{
    		if (_node->_right)
    		{
    			// 下一个就是右子树的最左节点
    			Node* left = _node->_right;
    			while (left->_left)
    			{
    				left = left->_left;
    			}
    
    			_node = left;
    		}
    		else
    		{
    			// 找祖先里面孩子不是祖先的右的那个
    			Node* parent = _node->_parent;
    			Node* cur = _node;
    			while (parent && cur == parent->_right)
    			{
    				cur = cur->_parent;
    				parent = parent->_parent;
    			}
    
    			_node = parent;
    		}
    
    		return *this;
    	}
    
    	Self& operator--()
    	{
    		if (_node->_left)
    		{
    			// 下一个是左子树的最右节点
    			Node* right = _node->_left;
    			while (right->_right)
    			{
    				right = right->_right;
    			}
    
    			_node = right;
    		}
    		else
    		{
    			// 孩子不是父亲的左的那个祖先
    			Node* parent = _node->_parent;
    			Node* cur = _node;
    			while (parent && cur == parent->_left)
    			{
    				cur = cur->_parent;
    				parent = parent->_parent;
    			}
    
    			_node = parent;
    		}
    
    		return *this;
    	}
    };
    
    template<class K, class T, class KeyOfT>
    struct RBTree
    {
    	typedef RBTreeNode<T> Node;
    public:
    	typedef __RBTreeIterator<T, T&, T*> iterator;
    
    	iterator begin()
    	{
    		Node* left = _root;
    		while (left && left->_left)
    		{
    			left = left->_left;
    		}
    
    		return iterator(left);
    	}
    
    	iterator end()
    	{
    		return iterator(nullptr);
    	}
    
    	pair<iterator, bool> Insert(const T& data)
    	{
    		KeyOfT kot;
    
    		if (_root == nullptr)
    		{
    			_root = new Node(data);
    			_root->_col = BLACK;
    			return make_pair(iterator(_root), true);
    		}
    
    		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 make_pair(iterator(cur), 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;
    
    		while (parent && parent->_col == RED)
    		{
    			Node* grandfater = parent->_parent;
    			assert(grandfater);
    			assert(grandfater->_col == BLACK);
    			// 关键看叔叔
    			if (parent == grandfater->_left)
    			{
    				Node* uncle = grandfater->_right;
    				// 情况一 : uncle存在且为红,变色+继续往上处理
    				if (uncle && uncle->_col == RED)
    				{
    					parent->_col = uncle->_col = BLACK;
    					grandfater->_col = RED;
    					// 继续往上处理
    					cur = grandfater;
    					parent = cur->_parent;
    				}// 情况二+三:uncle不存在 + 存在且为黑
    				else
    				{
    					// 情况二:右单旋+变色
    					if (cur == parent->_left)
    					{
    						RotateR(grandfater);
    						parent->_col = BLACK;
    						grandfater->_col = RED;
    					}
    					else
    					{
    						// 情况三:左右单旋+变色
    						RotateL(parent);
    						RotateR(grandfater);
    						cur->_col = BLACK;
    						grandfater->_col = RED;
    					}
    
    					break;
    				}
    			}
    			else // (parent == grandfater->_right)
    			{
    				Node* uncle = grandfater->_left;
    				// 情况一
    				if (uncle && uncle->_col == RED)
    				{
    					parent->_col = uncle->_col = BLACK;
    					grandfater->_col = RED;
    					// 继续往上处理
    					cur = grandfater;
    					parent = cur->_parent;
    				}
    				else
    				{
    					// 情况二:左单旋+变色
    					if (cur == parent->_right)
    					{
    						RotateL(grandfater);
    						parent->_col = BLACK;
    						grandfater->_col = RED;
    					}
    					else
    					{
    						// 情况三:右左单旋+变色
    						RotateR(parent);
    						RotateL(grandfater);
    						cur->_col = BLACK;
    						grandfater->_col = RED;
    					}
    
    					break;
    				}
    			}
    
    		}
    
    		_root->_col = BLACK;
    		return make_pair(iterator(newnode), true);
    	}
    
    	void InOrder()
    	{
    		_InOrder(_root);
    		cout << endl;
    	}
    
    	bool IsBalance()
    	{
    		if (_root == nullptr)
    		{
    			return true;
    		}
    
    		if (_root->_col == RED)
    		{
    			cout << "根节点不是黑色" << endl;
    			return false;
    		}
    
    		// 黑色节点数量基准值
    		int benchmark = 0;
    
    		return PrevCheck(_root, 0, benchmark);
    	}
    
    private:
    	bool PrevCheck(Node* root, int blackNum, int& benchmark)
    	{
    		if (root == nullptr)
    		{
    			if (benchmark == 0)
    			{
    				benchmark = blackNum;
    				return true;
    			}
    
    			if (blackNum != benchmark)
    			{
    				cout << "某条黑色节点的数量不相等" << endl;
    				return false;
    			}
    			else
    			{
    				return true;
    			}
    		}
    
    		if (root->_col == BLACK)
    		{
    			++blackNum;
    		}
    
    		if (root->_col == RED && root->_parent->_col == RED)
    		{
    			cout << "存在连续的红色节点" << endl;
    			return false;
    		}
    
    		return PrevCheck(root->_left, blackNum, benchmark)
    			&& PrevCheck(root->_right, blackNum, benchmark);
    	}
    
    	void _InOrder(Node* root)
    	{
    		if (root == nullptr)
    		{
    			return;
    		}
    
    		_InOrder(root->_left);
    		cout << root->_kv.first << ":" << root->_kv.second << endl;
    		_InOrder(root->_right);
    	}
    
    	void RotateL(Node* parent)
    	{
    		Node* subR = parent->_right;
    		Node* subRL = subR->_left;
    
    		parent->_right = subRL;
    		if (subRL)
    			subRL->_parent = parent;
    
    		Node* ppNode = parent->_parent;
    
    		subR->_left = parent;
    		parent->_parent = subR;
    
    		if (_root == parent)
    		{
    			_root = subR;
    			subR->_parent = nullptr;
    		}
    		else
    		{
    			if (ppNode->_left == parent)
    			{
    				ppNode->_left = subR;
    			}
    			else
    			{
    				ppNode->_right = subR;
    			}
    
    			subR->_parent = ppNode;
    		}
    
    	}
    
    	void RotateR(Node* parent)
    	{
    		Node* subL = parent->_left;
    		Node* subLR = subL->_right;
    
    		parent->_left = subLR;
    		if (subLR)
    		{
    			subLR->_parent = parent;
    		}
    
    		Node* ppNode = parent->_parent;
    
    		subL->_right = parent;
    		parent->_parent = subL;
    
    		if (_root == parent)
    		{
    			_root = subL;
    			subL->_parent = nullptr;
    		}
    		else
    		{
    			if (ppNode->_left == parent)
    			{
    				ppNode->_left = subL;
    			}
    			else
    			{
    				ppNode->_right = subL;
    			}
    
    			subL->_parent = ppNode;
    		}
    
    	}
    
    private:
    	Node* _root = nullptr;
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285
    • 286
    • 287
    • 288
    • 289
    • 290
    • 291
    • 292
    • 293
    • 294
    • 295
    • 296
    • 297
    • 298
    • 299
    • 300
    • 301
    • 302
    • 303
    • 304
    • 305
    • 306
    • 307
    • 308
    • 309
    • 310
    • 311
    • 312
    • 313
    • 314
    • 315
    • 316
    • 317
    • 318
    • 319
    • 320
    • 321
    • 322
    • 323
    • 324
    • 325
    • 326
    • 327
    • 328
    • 329
    • 330
    • 331
    • 332
    • 333
    • 334
    • 335
    • 336
    • 337
    • 338
    • 339
    • 340
    • 341
    • 342
    • 343
    • 344
    • 345
    • 346
    • 347
    • 348
    • 349
    • 350
    • 351
    • 352
    • 353
    • 354
    • 355
    • 356
    • 357
    • 358
    • 359
    • 360
    • 361
    • 362
    • 363
    • 364
    • 365
    • 366
    • 367
    • 368
    • 369
    • 370
    • 371
    • 372
    • 373
    • 374
    • 375
    • 376
    • 377
    • 378
    • 379
    • 380
    • 381
    • 382
    • 383
    • 384
    • 385
    • 386
    • 387
    • 388
    • 389
    • 390
    • 391
    • 392
    • 393
    • 394
    • 395
    • 396
    • 397
    • 398
    • 399
    • 400
    • 401
    • 402
    • 403
    • 404
    • 405
    • 406
    • 407
    • 408
    • 409
    • 410
    • 411
    • 412
    • 413
    • 414
    • 415
    • 416
    • 417
    • 418
    • 419
    • 420
    • 421

    简易封装map

    1. map封装代码

    #pragma once
    #include "RBTree.hpp"
    
    namespace yulao
    {
    	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<K, V>, MapKeyOfT>::iterator iterator;
    
    		iterator begin()
    		{
    			return _t.begin();
    		}
    
    		iterator end()
    		{
    			return _t.end();
    		}
    
    		pair<iterator, bool> insert(const pair<K, V>& kv)
    		{
    			return _t.Insert(kv);
    		}
    
    		V& operator[](const K& key)
    		{
    			pair<iterator, bool> ret = insert(make_pair(key, V()));
    			return ret.first->second;
    		}
    	private:
    		RBTree<K, pair<K, V>, MapKeyOfT> _t;
    	};
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42

    使用一个底层的红黑树 _t 来存储键-值对(pair)。以下是这个 map 类的主要特点和功能:

    1. 构造函数:map 类没有在提供的代码中实现构造函数,但可以自行添加。
    2. 迭代器:map 类定义了一个嵌套的 iterator 类型,这个迭代器是红黑树中的迭代器。begin() 函数返回红黑树中最小元素的迭代器,而 end() 函数返回表示结束位置的迭代器。这使得你可以使用迭代器来遍历 map 中的键-值对。
    3. 插入操作:insert 函数用于向 map 中插入键-值对。它通过调用底层红黑树 _tInsert 函数来执行插入操作,并返回一个 pair 对象,其中包含一个迭代器和一个布尔值。迭代器指向插入的元素,布尔值表示是否插入成功。如果插入的键已经存在,则返回的布尔值为 false,否则为 true
    4. 访问操作:operator[] 函数用于通过键访问 map 中的值。它首先调用 insert 函数尝试插入键-值对,然后返回插入的元素的值的引用。如果键已经存在,则不会插入新元素,而是返回已存在元素的引用。

    2. 测试map封装

    void test_map()
    {
        string arr[] = { "苹果", "西瓜", "苹果", "西瓜", "苹果", "苹果", "西瓜", "苹果", "香蕉", "苹果", "香蕉" };
    
        map<string, int> countMap;
        for (auto& str : arr)
        {
            // 1、str不在countMap中,插入pair(str, int()),然后在对返回次数++
            // 2、str在countMap中,返回value(次数)的引用,次数++;
            countMap[str]++;
        }
    
        map<string, int>::iterator it = countMap.begin();
        while (it != countMap.end())
        {
            cout << it->first << ":" << it->second << endl;
            ++it;
        }
    
        for (auto& kv : countMap)
        {
            cout << kv.first << ":" << kv.second << endl;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    输出结果

    苹果:6
    西瓜:3
    香蕉:2
    苹果:6
    西瓜:3
    香蕉:2
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    简易封装set

    1. set封装代码

    #pragma once
    #include "RBTree.hpp"
    
    namespace yulao
    {
    	template<class K>
    	class set
    	{
    		struct SetKeyOfT
    		{
    			const K& operator()(const K& key)
    			{
    				return key;
    			}
    		};
    	public:
    		typedef typename RBTree<K, K, SetKeyOfT>::iterator iterator;
    
    		iterator begin()
    		{
    			return _t.begin();
    		}
    
    		iterator end()
    		{
    			return _t.end();
    		}
    
    		pair<iterator, bool> insert(const K& key)
    		{
    			return _t.Insert(key);
    		}
    	private:
    		RBTree<K, K, SetKeyOfT> _t;
    	};
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    1. 构造函数:set 类没有在提供的代码中实现构造函数,但可以自行添加。
    2. 迭代器:set 类定义了一个嵌套的 iterator 类型,这个迭代器是红黑树中的迭代器。begin() 函数返回红黑树中最小元素的迭代器,而 end() 函数返回表示结束位置的迭代器。这使得你可以使用迭代器来遍历 set 中的元素。
    3. 插入操作:insert 函数用于向 set 中插入元素。它通过调用底层红黑树 _tInsert 函数来执行插入操作,并返回一个 pair 对象,其中包含一个迭代器和一个布尔值。迭代器指向插入的元素,布尔值表示是否插入成功。如果插入的元素已经存在,则返回的布尔值为 false,否则为 true

    2. 测试set封装

    void test_set()
    {
        set<int> s;
    
        set<int>::iterator it = s.begin();
        while (it != s.end())
        {
            cout << *it << " ";
            ++it;
        }
        cout << endl;
    
        s.insert(3);
        s.insert(2);
        s.insert(1);
        s.insert(5);
        s.insert(3);
        s.insert(6);
        s.insert(4);
        s.insert(9);
        s.insert(7);
    
    
        it = s.begin();
        while (it != s.end())
        {
            cout << *it << " ";
            ++it;
        }
        cout << endl;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    输出结果

    1 2 3 4 5 6 7 9
    
    • 1

    总结

    这里我们只是通过我们之前学习的红黑树的基础上做了一些模板上的修改,简单的实现了map和set的迭代器功能和插入功能,但这种使用红黑树底层模拟 mapset 的迭代器和插入功能的实现有以下作用和好处:

    1. 提供了自定义数据结构的能力: 通过使用底层红黑树实现 mapset,你可以更灵活地定义自己的数据结构,而不仅限于使用标准库提供的容器。这使得你可以根据特定的需求来设计和实现数据结构,以满足项目的要求。
    2. 学习数据结构和算法: 这种实现方式可以帮助你深入理解红黑树这种常用的自平衡二叉搜索树数据结构,以及与之相关的算法。通过手动实现红黑树的插入、删除和迭代器等功能,你可以更好地理解这些操作的内部工作原理,从而提高自己的编程技能。
    3. 适应特定需求: 有时标准库提供的容器不一定能满足特定项目或应用的需求。通过自定义数据结构,你可以根据自己的需求进行扩展和定制,以提供更适用的功能和性能。
    4. 教育和学术用途: 这种实现方式还可以用于教育和学术研究。它可以作为一个教学工具,帮助学生理解和学习红黑树等数据结构和算法的原理。同时,它也可以用于学术研究,用于开展相关领域的实验和研究。
  • 相关阅读:
    Python AI 在几秒钟内为我生成了这些 Python 应用程序——它们有用吗?
    GreaalVM编译springboot编译springboot
    vue服务端渲染ssr
    shiro学习33-shiro的工具类-webUtils
    Android R 11.x quickstep 手势导航架构和详细实现
    QT5-布局在创作中的理解应用
    设计模式之适配器模式
    如何管理和维护组件库?
    选择收银系统主要看哪些方面?
    聊一聊AI+BI数智融合,如何驱动企业数智化转型发展?
  • 原文地址:https://blog.csdn.net/kingxzq/article/details/132863240