• 【C++】封装map和set(红黑树实现)


    前言:

           前面,我们学习了set和map的用法,这两个容器可以完成查找,排序等操作,后来我们在学习过二叉搜索树的基础上又学习了两种特殊的二叉搜索树——AVL树和红黑树,他们俩可以是效率进一步提高,其实set和map的底层就是由红黑树封装而成的!

           所以,本篇文章我们自己学习用红黑树封装set和map。用红黑树封装,特别是用同一棵红黑树实现封装有一定的难度,其中很多操作(比如复用)我们会第一次尝试,所以大家请跟紧作者的脚步来。

    目录

    (一)如何复用同一棵红黑树

    (二)红黑树的改造流程(为封装做铺垫)

    1、结点的定义

    2、模拟实现结点的比较大小

    3、改造后的红黑树

    4、map和set迭代器的模拟实现

    4.1模版参数的构成

    4.2begin()和end()的模拟实现

    4.3operator* 和 operator->模拟实现

    4.4 operator++ 和 operator--模拟实现

    4.5 operator== 和 operator!=模拟实现

    4.6迭代器代码详解

     (三)封装map和set


    (一)如何复用同一棵红黑树

    前提疑问:

    在我们这所有的之前我们知道,map和set这两个容器都是用红黑树来实现的,那么就有了接下来的问题。

    • map和set都是用的同一棵红黑树复用的吗
    • 或者这两个容器各自使用一棵红黑树吗

    其实在前言中我们就知道了,根据STL的设计理念和泛型编程的理念,我们不会冗余的写两课红黑树,而是用一棵红黑树实现复用的效果。

    我们调用STL库中的原码来看:

    我们发现:

    • STL库中的原码也确实调用的同一棵红黑树
    • 他们实现的都是key_value模型

    我们设set中存放结点的值是K,map中存放的节点是pair键值对:

    • 对于set而言,底层红黑树的模版就是RBTree
    • 对于map而言,底层红黑树的模版就是RBTree>

    这时我们就有了另一个疑问,两个模板参数的第一个Key,不能省略掉吗??

    • 首先,答案肯定是不能的
    • 那么原因又是什么呢?

    因为map的这个类中,无论怎么省略都会有一个查找函数要单独用到Key

    如果第一个Key删去了,那么map和set的查找函数就没法统一实现了,违背了我们一开始泛型编程的思想。

    综上所述:

    • map和set都是用了,Key_value模型
    • set中的K是K,V也是K
    • map中的K是K,V是pair
    • 并且模板参数中第一个K都不能省

    (二)红黑树的改造流程(为封装做铺垫)

    1、结点的定义

    这里由于set和map存放的结点一个是Key一个是pair,所以我们使用模版,把存放的结点泛化。

    2、模拟实现结点的比较大小

    • 上述提到,在模拟实现中,map和set我们复用同一棵红黑树的时候都是用的是Kye_value的结构
    • 但是红黑树中的数据比较又是Key值的比较,而现在我们用的则是pair的比较
    • 虽然编译上是可以通过但是真的就是我们所想要的吗?

    pair的比较大小:

    很显然这种比较规则不是我们所想要的,并且map和set想要取到用来比较的数据是不同的。 

    为了取到我们想要的数据,我们引入了仿函数:

    • 根据map和set的需求不同
    • 我们在红黑树中新引入了一个模板参数KeyOfT

     

    引入KeyOfT模板参数后,我们想要不同方式的比较方法只需要在set和map的封装中给出属于他们自己的比较仿函数。

    map中的仿函数: 

    set中的仿函数:

    使用方法:

     此时前面所说的仿函数的便利之处就体现出来了。

    3、改造后的红黑树

    具体代码:

    1. //红黑树的实现
    2. //KeyOfT --> 支持取出T对象中key的仿函数
    3. template<class K, class T, class KeyOfT>
    4. class RBTree
    5. {
    6. typedef RBTreeNode<T> Node;
    7. public:
    8. typedef __RBTreeIterator<T, T&, T*> iterator;
    9. typedef __RBTreeIterator<T, const T&, const T*> const_iterator;
    10. //构造 拷贝构造 赋值 和析构 跟搜索树实现方式是一样的
    11. //迭代器中序遍历,要找最左结点
    12. iterator Begin()
    13. {
    14. Node* subLeft = _root;
    15. while (subLeft && subLeft->_left)
    16. {
    17. subLeft = subLeft->_left;
    18. }
    19. //树的迭代器用结点的指针就可以构造
    20. return iterator(subLeft);
    21. }
    22. iterator End()
    23. {
    24. return iterator(nullptr);
    25. }
    26. const_iterator Begin() const
    27. {
    28. Node* subLeft = _root;
    29. while (subLeft && subLeft->_left)
    30. {
    31. subLeft = subLeft->_left;
    32. }
    33. //树的迭代器用结点的指针就可以构造
    34. return const_iterator(subLeft);
    35. }
    36. const_iterator End() const
    37. {
    38. return const_iterator(nullptr);
    39. }
    40. pair<iterator, bool> Insert(const T& data)
    41. {
    42. //1、搜索树的规则插入
    43. //2、看是否违反平衡规则,如果违反就需要处理:旋转
    44. if (_root == nullptr)
    45. {
    46. _root = new Node(data);
    47. _root->_col = BLACK; //根节点是黑色
    48. return make_pair(iterator(_root), true);
    49. }
    50. KeyOfT kot;
    51. Node* parent = nullptr;
    52. Node* cur = _root;
    53. while (cur)
    54. {
    55. if (kot(cur->_data) < kot(data))
    56. {
    57. parent = cur;
    58. cur = cur->_right;
    59. }
    60. else if (kot(cur->_data) > kot(data))
    61. {
    62. parent = cur;
    63. cur = cur->_left;
    64. }
    65. else
    66. {
    67. return make_pair(iterator(cur), false);
    68. }
    69. }
    70. //找到符合规则的位置之后再插入
    71. cur = new Node(data);
    72. Node* newnode = cur;
    73. cur->_col = RED;
    74. if (kot(parent->_data) < kot(data))
    75. {
    76. parent->_right = cur;
    77. }
    78. else
    79. {
    80. parent->_left = cur;
    81. }
    82. //三叉链的链接 -- 链上父节点
    83. cur->_parent = parent;
    84. //存在连续红色结点
    85. while (parent && parent->_col == RED)
    86. {
    87. //理论而言,祖父是一定存在的,父亲存在且是红不可能是根(根一定是黑的)
    88. Node* grandfather = parent->_parent;
    89. assert(grandfather);
    90. if (grandfather->_left == parent)
    91. {
    92. Node* uncle = grandfather->_right;
    93. //情况一:(叔叔存在且为红)
    94. if (uncle && uncle->_col == RED)
    95. {
    96. //祖父和叔叔变成黑色
    97. parent->_col = uncle->_col = BLACK;
    98. grandfather->_col = RED;
    99. //继续往上处理
    100. cur = grandfather;
    101. parent = cur->_parent;
    102. }
    103. //情况二:(叔叔不存在 or 叔叔存在且为黑)
    104. else
    105. {
    106. //单旋
    107. // g
    108. // p
    109. // c
    110. if (cur == parent->_left)
    111. {
    112. RotateR(grandfather);
    113. parent->_col = BLACK;
    114. grandfather->_col = RED;
    115. }
    116. //双旋
    117. // g
    118. // p
    119. // c
    120. else
    121. {
    122. RotateL(parent);
    123. RotateR(grandfather);
    124. cur->_col = BLACK;
    125. grandfather->_col = RED;
    126. }
    127. break;
    128. }
    129. }
    130. //无论父亲和叔叔是左是右都是一样的
    131. //grandfather->_right == parent;
    132. else
    133. {
    134. Node* uncle = grandfather->_left;
    135. //情况一:
    136. if (uncle && uncle->_col == RED)
    137. {
    138. //祖父和叔叔变成黑色
    139. parent->_col = uncle->_col = BLACK;
    140. grandfather->_col = RED;
    141. //继续往上处理
    142. cur = grandfather;
    143. parent = cur->_parent;
    144. }
    145. else
    146. {
    147. //单旋
    148. // g
    149. // p
    150. // c
    151. if (cur == parent->_right)
    152. {
    153. RotateL(grandfather);
    154. parent->_col = BLACK;
    155. grandfather->_col = RED;
    156. }
    157. //双旋
    158. // g
    159. // p
    160. // c
    161. else
    162. {
    163. RotateR(parent);
    164. RotateL(grandfather);
    165. cur->_col = BLACK;
    166. grandfather->_col = RED;
    167. }
    168. break;
    169. }
    170. }
    171. }
    172. //父亲为空就出循环,将根节点设置成黑色
    173. _root->_col = BLACK;
    174. return make_pair(iterator(newnode), true);
    175. }
    176. }

    插入(Insert)和寻找(Find)代码:
     

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

    4、map和set迭代器的模拟实现

    上面改造后的红黑树中已经涉及到了迭代器,这里我们来模拟实现。

    备注:

    • T:数据
    • Ref:引用
    • Ptr:指针
    • Sef:iterator本身

    4.1模版参数的构成

    要想实现同一棵红黑树的复用,模版参数的构成极为重要。

    之前我们也遇到过相似的情况,我们这里的实现方法参看之前。

    迭代器的实现中:

    • 涉及到了*解引用操作,返回的是数据的引用;
    • 涉及到了->指针操作,返回的是数据的地址;
    • 涉及到++,--操作,返回的是操作后迭代器本身的位置。

    但是以上的行为,我们都涉及结点,所以结点的数据类型也尤为重要

    综上,模版参数的构成如下图:

    4.2begin()和end()的模拟实现

    • 因为是二叉搜索树,为了更有顺序,所以我们采取的是中序遍历。
    • 那么中序遍历Begin()就应该是最左结点
    • 我们实现的版本中End()定义为空是(nullptr)

    ps:

    而库中的红黑树则是设计了一个哨兵位的头结点:

    所以我们实现的只是简化版本。

    4.3operator* 和 operator->模拟实现

    就是正常的运用operator,但是operator->和list中讲的一样,返回的是地址的原因是为了连续访问(连续的operator->会优化成一个->)

    4.4 operator++ 和 operator--模拟实现

    这里迭代器的++和- - 需要分类一下,分别是:前置++,- - 、后置++,- -

    前置++ :
    因为我们是中序遍历,我们访问完自己之后,下一个该访问哪一个结点?

    我们观察任何一棵二叉树都能看出,无非是下面两种情况:

    分如下两种情况:(重点)

    • 右子树为空:找孩子是父亲的左的那个祖先节点,否则继续往上走,直到空(nullptr)
    • 右子树为非空:找右子树的最左节点

    这一过程有点类似于递归思想,但是是非递归实现的

    代码实现:

     前置-- :

    有了上面的思路,我们联想一下,现在需要看当前位置左子树是否是空。

    前置- -就是倒着走,同样还是对当前位置分两种情况:(重点)

    1. 左子树为空:找孩子是父亲的右的那个祖先节点,否则继续往上走,直到空(nullptr)
    2. 左子树为非空:找左子树的最右节点

    只要前置++理解了,那么前置- -完全就是前置++倒过来走一遍。

    后置++、后置- - :

    和之前实现容器的得带器一样,我们这里直接复用即可:

    4.5 operator== 和 operator!=模拟实现

    有了之前封装迭代器的经验,这两个的视线还是比较容易得:

    4.6迭代器代码详解

    1. template<class T, class Ref, class Ptr>
    2. struct __RBTreeIterator
    3. {
    4. typedef RBTreeNode<T> Node;
    5. Node* _node;
    6. typedef __RBTreeIterator<T, Ref, Ptr> Self;
    7. __RBTreeIterator(Node* node)
    8. :_node(node)
    9. {}
    10. Ref operator*()
    11. {
    12. return _node->_data;
    13. }
    14. Ptr operator->()
    15. {
    16. return &_node->_data;
    17. }
    18. Self& operator++()
    19. {
    20. if (_node->_right == nullptr)
    21. {
    22. //找祖先里面,孩子是父亲左的那个
    23. Node* cur = _node;
    24. Node* parent = cur->_parent;
    25. while (parent && parent->_right == cur)
    26. {
    27. cur = cur->_parent;
    28. parent = parent->_parent;
    29. }
    30. _node = parent;
    31. }
    32. else
    33. {
    34. //右子树的最左结点
    35. Node* subLeft = _node->_right;
    36. while (subLeft->_left)
    37. {
    38. subLeft = subLeft->_left;
    39. }
    40. //左为空
    41. _node = subLeft;
    42. }
    43. return *this;
    44. }
    45. Self& operator--()
    46. {
    47. if (_node->_left == nullptr)
    48. {
    49. //找祖先里面,孩子是父亲
    50. Node* cur = _node;
    51. Node* parent = cur->_parent;
    52. while (parent && cur == parent->_left)
    53. {
    54. cur = cur->_parent;
    55. parent = parent->_parent;
    56. }
    57. _node = parent;
    58. }
    59. else
    60. {
    61. //左子树的最右结点
    62. Node* subRight = _node->_left;
    63. while (subRight->_right)
    64. {
    65. subRight = subRight->_right;
    66. }
    67. _node = subRight;
    68. }
    69. return *this;
    70. }
    71. Self operator++(int)
    72. {
    73. Self tmp(*this);
    74. ++(*this);
    75. return tmp;
    76. }
    77. Self operator--(int)
    78. {
    79. Self tmp(*this);
    80. --(*this);
    81. return tmp;
    82. }
    83. bool operator!=(const Self& s) const
    84. {
    85. return _node != s._node;
    86. }
    87. bool operator==(const Self& s) const
    88. {
    89. return _node == s._node;
    90. }
    91. };

     (三)封装map和set

    有了上面的红黑树的改装,我们这里的对map和set的封装就显得很得心应手了。

    封装主要是把map和set的基本操作封装在一个类中。

    map的封装:

    1. template<class K, class V>
    2. class map
    3. {
    4. //定义一个内部类
    5. struct MapKeyOfT
    6. {
    7. const K& operator()(const pair<K, V>& kv)//operator() 可以像函数一样去使用
    8. {
    9. return kv.first;
    10. }
    11. };
    12. public:
    13. typedef typename RBTree<K, pair<K, V>, MapKeyOfT>::iterator iterator;
    14. typedef typename RBTree<K, pair<K, V>, MapKeyOfT>::const_iterator const_iterator;
    15. iterator begin()
    16. {
    17. return _t.Begin();
    18. }
    19. iterator end()
    20. {
    21. return _t.End();
    22. }
    23. pair<iterator, bool> insert(const pair<K, V>& kv)
    24. {
    25. return _t.Insert(kv);
    26. }
    27. V& operator[](const K& key)
    28. {
    29. pair<iterator, bool> ret = insert(make_pair(key, V()));
    30. return ret.first->second;
    31. }
    32. private:
    33. RBTree<K, pair<K, V>, MapKeyOfT> _t;
    34. };

    这里map中的operator[ ]我们知道其原理之后,模拟实现就非常方便,直接调用插入函数,控制好参数和返回值即可。

    对set的封装:

    1. template<class K>
    2. class set
    3. {
    4. struct SetKeyOfT
    5. {
    6. const K& operator()(const K& key)//operator() 可以像函数一样去使用
    7. {
    8. return key;
    9. }
    10. };
    11. public:
    12. //加上typename告诉编译器这是个类型,类模板实例化了再去取
    13. typedef typename RBTree<K, K, SetKeyOfT>::const_iterator iterator;
    14. typedef typename RBTree<K, K, SetKeyOfT>::const_iterator const_iterator;
    15. iterator begin() const
    16. {
    17. return _t.Begin();
    18. }
    19. iterator end() const
    20. {
    21. return _t.End();
    22. }
    23. pair<iterator, bool> insert(const K& key)
    24. {
    25. //pair<typename RBTree<K, K, SetKeyOfT>::iterator, bool> ret = _t.Insert(key);
    26. auto ret = _t.Insert(key);
    27. return pair<iterator, bool>(iterator(ret.first._node), ret.second);
    28. }
    29. iterator find(const K& key)
    30. {
    31. return _t.Find(key);
    32. }
    33. private:
    34. RBTree<K, K, SetKeyOfT> _t;
    35. };

    附详细代码:——》红黑树封装map和set

  • 相关阅读:
    MySql学习笔记10——视图介绍
    Pinyin4j介绍和简单使用
    全网最全JAVA面试八股文,终于整理完了
    50天50个前端小项目(纯html+css+js)第十八天(背景轮播图)
    Beelzebub过程记录及工具集
    RBF神经网络案例——客户流失率预测
    Opencv基于文字检测去图片水印
    Codeforces Round 958 (Div. 2)[部分题解ABC]
    Stable Diffussion和MJ的详细对比
    MySQL中的事务
  • 原文地址:https://blog.csdn.net/m0_67821824/article/details/132767277