【C++篇】红黑树封装 实现map和set

打印 上一主题 下一主题

主题 950|帖子 950|积分 2850

目录

前言:
一,库中map和set的大致结构
二,模仿实现
2.1,大致框架
2.2,复用红黑树实现insert接口
 2.3,迭代器iterator的实现
operator++()的实现:
operator--()的实现:
对insert返回值的更改:
2.4,map支持[ ]
2.5,团体代码 
2.6,代码测试


前言:

本篇基于上篇【红黑树的实现】,代码也是基于红黑树的代码实现map和set的封装。
一,库中map和set的大致结构

库中部分源代码如下:
   //set
  class set {   
public:
  // typedefs:

    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;  // red-black tree representing set

  };
  
    //map
  class map {   
public:

    //typedefs:
    typedef Key key_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;  // red-black tree representing map

  };
  
    //rb_tree红黑树 
  template <class Value>
struct __rb_tree_node : public __rb_tree_node_base
{   
  typedef __rb_tree_node<Value>* link_type;
  Value value_field;
};

  
  template <class Key, class Value, class KeyOfValue, class Compare,
          class Alloc = alloc>
class rb_tree {   

     typedef __rb_tree_node<Value> rb_tree_node;
     typedef rb_tree_node* link_type;
  };
          通过上面的源码可以分析出,map和set的实现采取了泛型头脑实现。本来map和set各需要一颗红黑树rb_tree来实现的,如许的话两份代码相似部分极多。而采取泛型的头脑,让rb_tree成为一个泛型模板,通过传参的差异决定是 map还是set,如许只需一份rb_tree即可。
        rb_tree是实现key的搜刮场景,还是实现key/value的搜刮场景,是通过第二个模板参数Value决定的,Value的类型确定了,__rb_tree的存储数据的类型就确定了。
        对于set,它的底层封装了rb_tree,第二个模板参数传的是key,实例化出的rb_tree,就是支持key的搜刮场景。
        对于map,它的底层也封装了rb_tree,第二个参数传的是pair<const k,v>,实例化出的rb_tree,就是支持key/value的搜刮场景。
           尚有一点,对于map和set,我们可以知道关键在于底层rb_tree的第二个模板参数,那为什么还要再传第一个模板参数?        
          对于set类型,通过源码可以发现,底层rb_tree的第一个模板参数和第二个模板参数其实是一样的,都是key。但对于map来说,底层rb_tree的第一个模板参数是key,第二个模板参数是pair<k,v>。由于我们在利用rb_tree的查找(find)接口时,是根据key值来查找的,以是需要传第一个模板参数key。可以认为对于set来说时多余的,而对于map来说是必不可少的。为了实今世码的统一,以是set也要传。
  
 

二,模仿实现

2.1,大致框架

set.h
  1. #include "RBTree.h"
  2. //xg
  3. //key
  4. namespace xg
  5. {
  6.         template<class k>
  7.         class set
  8.         {
  9.         public:
  10.         //...
  11.         private:
  12.                 //底层调用红黑树
  13.         //k键值是不能修改的,所以 加上const
  14.                 RBTree<k, const k> _t;
  15.         };
  16. }
复制代码
 map.h
  1. #include "RBTree.h"
  2. //map
  3. //pair<k,v>
  4. namespace xg
  5. {
  6.         template<class k,class v>
  7.         class map
  8.         {
  9.         public:
  10.         //...
  11.         private:
  12.                 //底层调用红黑树
  13.         //key值不能修改
  14.                 RBTree<k, pair<const k, v>> _t;
  15.         };
  16. }
复制代码
同时,我们也采取库中的方法,对rb_tree进行修改,使其成为一个泛型结构。
rb_tree.h
  1. #include <iostream>
  2. using namespace std;
  3. enum color
  4. {
  5.         Red,
  6.         Black
  7. };
  8. //由类型T决定红黑树为key还是pair类型
  9. template<class T>
  10. struct RBTreeNode
  11. {
  12.         RBTreeNode(const T& data)
  13.                 :_left(nullptr)
  14.                 ,_right(nullptr)
  15.                 ,_parent(nullptr)
  16.                 ,_data(data)
  17.         {}
  18.         RBTreeNode<T>* _left;
  19.         RBTreeNode<T>* _right;
  20.         RBTreeNode<T>* _parent;
  21.         T _data;
  22.         color _col;      
  23. };
  24. //T决定是k还是pair
  25. template<class k,class T>
  26. class RBTree
  27. {
  28. public:
  29.         typedef RBTreeNode<T> Node;
  30.     //...
  31. private:
  32.         Node* _root=nullptr;
  33. };
复制代码
2.2,复用红黑树实现insert接口

对于set和map,底层直接调用红黑树rb_tree的insert接口。
   //set
  bool insert(const k& key)
{   
    return _t.Insert(key);
}
  //map
  bool insert(const pair<k, v>& kv)
{   
    return _t.Insert(kv);
}
  我们看看rb_tree中的insert接口(部分代码):

这里需要将参数类型改为T类型,由map和set决定它的类型是key还是pair。
   在插入逻辑中,我们需要比较插入元素的key值,从而找到插入位置。
  对于set,比较的就是key值。但是对于map,比较的就是kv.fist。
  为了满足两种不同的比较,我们可以通过仿函数的方式实现。map和set各实现一个仿函数,用来获取各自的key值。
  通过分析源码可知,map和set的第三个模板参数就是为了解决这个题目。
   set.h
  1. #include "RBTree.h"
  2. //xg
  3. //key
  4. namespace xg
  5. {
  6.         template<class k>
  7.         class set
  8.         {
  9.         public:
  10.                 struct SetOfk
  11.                 {
  12.                         const k& operator()(const k& key)
  13.                         {
  14.                                 return key;
  15.                         }
  16.                 };
  17.     bool insert(const k& key)
  18.     {
  19.             return _t.Insert(key);
  20.     }
  21.         private:
  22.                 //底层调用红黑树
  23.                 RBTree<k, const k,SetOfk> _t;
  24.         };
  25. }
复制代码
map.h
  1. #include "RBTree.h"
  2. //map
  3. //pair<k,v>
  4. namespace xg
  5. {
  6.         template<class k,class v>
  7.         class map
  8.         {
  9.         public:
  10.                 struct MapOfk
  11.                 {
  12.                         const k& operator()(const pair<k, v>& kv)
  13.                         {
  14.                                 return kv.first;
  15.                         }
  16.                 };
  17.         bool insert(const pair<k, v>& kv)
  18.         {
  19.                 return _t.Insert(kv);
  20.         }
  21.         private:
  22.                 //底层调用红黑树
  23.                 RBTree<k, pair<const k, v>,MapOfk> _t;
  24.         };
  25. }
复制代码
rb_tree的insert部分:
   template<class k,class T,class ValueOfk>
class RBTree{   
  //插入k或者pair类型
bool  Insert(const T& data)
{   
    if (_root == nullptr)
    {   
        _root = new Node(data);
        _root->_col = Black;
        //return pair<Iterator,bool>({_root,_root},true);
        return {Iterator(_root,_root),true};
    }
    ValueOfk kot;
    Node* cur = _root;
    Node* parent = nullptr;
    while (cur)
    {   
        //用键值k比较
        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;
        }
    }
        //......旋转+变色
          //......
          //......
  }
  };
   2.3,迭代器iterator的实现

迭代器本质上是对红黑树节点的封装。我们需要实现对*,->的重载,以及对++,--的实现。
  1. template<class T,class Ref,class ptr>
  2. class RBTreeIterator
  3. {
  4. public:
  5.         typedef RBTreeNode<T> Node;
  6.         typedef RBTreeIterator<T, Ref, ptr> Self;
  7.         RBTreeIterator(Node* node)
  8.                 :_node(node)
  9.         {}
  10.     //......
  11.     //......
  12. private:
  13.                 //当前节点
  14.                 Node* _node;
  15. };
复制代码
这里的迭代器实现与list的迭代器实现思绪大致雷同,通过传Ref和ptr两个参数,从而通过一份模板,实现出iterator和const_iterator.
一些操纵符的重载:
   Ref operator*()
{   
    return _node->_data;
}
ptr operator->()
{   
    return &_node->_data;
}
bool operator!=(const Self& s) const
{   
    return s._node != _node;
}
bool operator==(const Self& s) const 
{   
    return s._node == _node;
}
  operator++()的实现:

    (1)起首,我们要知道map和set的迭代器遍历走的是中序遍历,左子树->根节点->右子树,那么begin()应该返回 中序第一个节点,也就是红黑树的最左节点。而对于end(),我们可以让它是空节点。
  (2)迭代器++时,如果it指向的节点的右子树不为空时,说明当前节点已经访问完,下一个节点访问是右子树的中序第一个,也就是右子树的最左节点
  (3)迭代器++时,如果it指向的节点的右子树为空,说明当前节点已经当前节点所在的子树已经访问完了,要访问的下一个节点在当前节点的祖先里面,要沿着当前节点到根的路径找。并且该节点一定满足孩子是父亲的左子树。
  

 
  1. Self operator++()
  2. {
  3.         //左根右
  4.         //当前节点的右子树不为空,继续找右子树的最左节点
  5.         if (_node->_right)
  6.         {
  7.                 Node* cur = _node->_right;
  8.                 while ( cur->_left)
  9.                 {
  10.                         cur = cur->_left;
  11.                 }
  12.                 _node = cur;
  13.         }
  14.         else
  15.         {
  16.                 //当前节点的右子树为空,说明当前子树已经访问完
  17.                 //找孩子为祖先左的祖先
  18.                 Node* cur = _node;
  19.                 Node* parent = cur->_parent;
  20.                 while (parent && cur == parent->_right)
  21.                 {
  22.                         cur = parent;
  23.                         parent = cur->_parent;
  24.                 }
  25.                 _node = parent;
  26.         }
  27.         return *this;
  28. }
复制代码
operator--()的实现:

实现思绪与operator++()相反
   (1)迭代器--时,如果it指向的节点的左子树不为空时,说明当前节点已经访问完,下一个节点访问是左子树的最右节点
  (2)迭代器--时,如果it指向的节点的左子树为空,说明当前节点已经当前节点所在的子树已经访问完了,要访问的下一个节点在当前节点的祖先里面,要沿着当前节点到根的路径找。并且该节点一定满足孩子是父亲的右子树。
  (3)需要注意的是,大概会遇到end()--的环境,而end()是空节点,会报错。我们可以进行特殊处置惩罚,当it==end()时,让 它等于中序遍历的末了一个节点,也就是红黑树的最右节点
  而在最右节点的时候,需要根节点,以是需要在iterator中再加入根节点。
  1. Self operator--()
  2. {
  3.         //右根左
  4.         if (_node == nullptr) //end()--
  5.         {
  6.                 Node* cur = _root;
  7.                 while (cur->_right)
  8.                 {
  9.                         cur = cur->_right;
  10.                 }
  11.                 _node = cur;
  12.         }
  13.         //当前节点的左子树不为空,继续找左子树的最右节点
  14.         else if (_node->_left)
  15.         {
  16.                 Node* cur = _node->_left;
  17.                 while (cur)
  18.                 {
  19.                         cur = cur->_right;
  20.                 }
  21.                 _node = cur;
  22.         }
  23.         else
  24.         {
  25.                 //左子树为空,当前子树已访问完
  26.                 //找孩子为祖先右的节点
  27.                 Node* cur = _node;
  28.                 Node* parent = cur->_parent;
  29.                 while (parent && cur == parent->_left)
  30.                 {
  31.                         cur = parent;
  32.                         parent = cur->_parent;
  33.                 }
  34.                 _node = parent;
  35.         }
  36.         return *this;
  37. }
复制代码
对insert返回值的更改:


 

库中的insert方法实现了返回pair<iterator,bool>类型,iterator表示 插入节点的迭代器,bool值表示是否插入乐成。 我们只需在返回值处修改,返回iterator迭代器和bool构成的pair类型。
   //插入k或者pair类型
pair<Iterator,bool> Insert(const T& data)
{   
    if (_root == nullptr)
    {   
        _root = new Node(data);
        _root->_col = Black;
        //return pair<Iterator,bool>({_root,_root},true);
        return {Iterator(_root,_root),true};
    }
    ValueOfk kot;
    Node* cur = _root;
    Node* parent = nullptr;
    while (cur)
    {   
        //用键值k比较
        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 pair<Iterator,bool>({cur,_root},false);
            return { Iterator(cur, _root), false };
        }
    }
      //插入
    cur = new Node(data);
       //cur在下述调解过程中会向上更新变革,需要提前生存下来
    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* grandfather = parent->_parent;
        if (parent == grandfather->_left)
        {   
            //    g
            //  p   u
            Node* uncle = grandfather->_right;
            //叔叔存在且为红
            if (uncle && uncle->_col == Red)
            {   
                //变色
                parent->_col = Black;
                uncle->_col = Black;
                grandfather->_col = Red;
                //继续向上处置惩罚
                cur = grandfather;
                parent = cur->_parent;
            }
            else
            {   
                //叔叔不存在或者叔叔为黑
                //    g
                //  p   u
               // c
                //u为黑,则c是之前是黑的
                //u不存在,则c是新插入的
                if (cur == parent->_left)
                {   
                    RotateR(grandfather);
                    parent->_col = Black;
                    grandfather->_col = Red;
                }
                else
                {   
                    //    g
                    //  p   u
                   //     c
                    RotateL(parent);
                    RotateR(grandfather);
                    cur->_col = Black;
                    grandfather->_col = Red;
                }
                break;
            }
        }
        else
        {   
            //   g
            // u   p
            Node* uncle = grandfather->_left;
            if (uncle && uncle->_col == Red)
            {   
                //变色
                parent->_col = Black;
                uncle->_col = Black;
                grandfather->_col = Red;
                  cur = grandfather;
                parent = cur->_parent;
            }
            else
            {   
                //   g
                // u   p
                //       c
                if (cur == parent->_right)
                {   
                    RotateL(grandfather);
                    parent->_col = Black;
                    grandfather->_col = Red;
                }
                else
                {   
                    //   g
                    // u   p
                    //   c
                    RotateR(parent);
                    RotateL(grandfather);
                    cur->_col = Black;
                    grandfather->_col = Red;
                }
                break;
            }
        }
    }
    _root->_col = Black;
    return pair<Iterator,bool>({newnode,_root},true);
}
  2.4,map支持[ ]

map需要支持operator[ ]来实现对value值的访问及修改
我们在上述实现了insert接口返回pair<iterator,bool>类型,就可以直接复用。
    v& operator[](const k& key)   
{   
       //key不存在就插入该值和value的缺省值,并返回
       //key存在就得到key位置的iterator
    pair<iterator, bool> ret = insert({ key,v() });
    return ret.first->second;
}
  2.5,团体代码 

rb_tree.h
  1. #include <iostream>
  2. using namespace std;
  3. enum color
  4. {
  5.         Red,
  6.         Black
  7. };
  8. //由类型T决定红黑树为key还是pair类型
  9. template<class T>
  10. struct RBTreeNode
  11. {
  12.         RBTreeNode(const T& data)
  13.                 :_left(nullptr)
  14.                 ,_right(nullptr)
  15.                 ,_parent(nullptr)
  16.                 ,_data(data)
  17.         {}
  18.         RBTreeNode<T>* _left;
  19.         RBTreeNode<T>* _right;
  20.         RBTreeNode<T>* _parent;
  21.         T _data;
  22.         color _col;      
  23. };
  24. template<class T,class Ref,class ptr>
  25. class RBTreeIterator
  26. {
  27. public:
  28.         typedef RBTreeNode<T> Node;
  29.         typedef RBTreeIterator<T, Ref, ptr> Self;
  30.         RBTreeIterator(Node* node,Node* root)
  31.                 :_node(node)
  32.                 ,_root(root)
  33.         {}
  34.         Self operator++()
  35.         {
  36.                 //左根右
  37.                 //当前节点的右子树不为空,继续找右子树的最左节点
  38.                 if (_node->_right)
  39.                 {
  40.                         Node* cur = _node->_right;
  41.                         while ( cur->_left)
  42.                         {
  43.                                 cur = cur->_left;
  44.                         }
  45.                         _node = cur;
  46.                 }
  47.                 else
  48.                 {
  49.                         //当前节点的右子树为空,说明当前子树已经访问完
  50.                         //找孩子为祖先左的祖先
  51.                         Node* cur = _node;
  52.                         Node* parent = cur->_parent;
  53.                         while (parent && cur == parent->_right)
  54.                         {
  55.                                 cur = parent;
  56.                                 parent = cur->_parent;
  57.                         }
  58.                         _node = parent;
  59.                 }
  60.                 return *this;
  61.         }
  62.         Self operator--()
  63.         {
  64.                 //右根左
  65.                 if (_node == nullptr) //end()--
  66.                 {
  67.                         Node* cur = _root;
  68.                         while (cur->_right)
  69.                         {
  70.                                 cur = cur->_right;
  71.                         }
  72.                         _node = cur;
  73.                 }
  74.                 //当前节点的左子树不为空,继续找左子树的最右节点
  75.                 else if (_node->_left)
  76.                 {
  77.                         Node* cur = _node->_left;
  78.                         while (cur)
  79.                         {
  80.                                 cur = cur->_right;
  81.                         }
  82.                         _node = cur;
  83.                 }
  84.                 else
  85.                 {
  86.                         //左子树为空,当前子树已访问完
  87.                         //找孩子为祖先右的节点
  88.                         Node* cur = _node;
  89.                         Node* parent = cur->_parent;
  90.                         while (parent && cur == parent->_left)
  91.                         {
  92.                                 cur = parent;
  93.                                 parent = cur->_parent;
  94.                         }
  95.                         _node = parent;
  96.                 }
  97.                 return *this;
  98.         }
  99.         Ref operator*()
  100.         {
  101.                 return _node->_data;
  102.         }
  103.         ptr operator->()
  104.         {
  105.                 return &_node->_data;
  106.         }
  107.         bool operator!=(const Self& s) const//请const吃一顿
  108.         {
  109.                 return s._node != _node;
  110.         }
  111.         bool operator==(const Self& s) const //请coonst吃一顿
  112.         {
  113.                 return s._node == _node;
  114.         }
  115. private:
  116.                 //当前节点
  117.                 Node* _node;
  118.                 Node* _root;//根节点
  119. };
  120. //T决定是k还是pair
  121. template<class k,class T,class ValueOfk>
  122. class RBTree
  123. {
  124. public:
  125.         typedef RBTreeNode<T> Node;
  126.         typedef RBTreeIterator<T, T&, T*>  Iterator;
  127.         typedef RBTreeIterator<T, const T&, const T*> ConstIterator;
  128.         //迭代器为中序遍历
  129.         Iterator Begin()
  130.         {
  131.                 //找最左节点
  132.                 Node* cur = _root;
  133.                 while (cur&&cur->_left)
  134.                 {
  135.                         cur = cur->_left;
  136.                 }
  137.                 return Iterator(cur,_root);
  138.         }
  139.         Iterator End()
  140.         {
  141.                 return Iterator(nullptr,_root);
  142.         }
  143.         ConstIterator Begin() const
  144.         {
  145.                 Node* cur = _root;
  146.                 while (cur && cur->_left)
  147.                 {
  148.                         cur = cur->_left;
  149.                 }
  150.                 return ConstIterator(cur,_root);
  151.         }
  152.         ConstIterator End() const
  153.         {
  154.                 return ConstIterator(nullptr,_root);
  155.         }
  156.         //插入k或者pair类型
  157.         pair<Iterator,bool> Insert(const T& data)
  158.         {
  159.                 if (_root == nullptr)
  160.                 {
  161.                         _root = new Node(data);
  162.                         _root->_col = Black;
  163.                         //return pair<Iterator,bool>({_root,_root},true);
  164.                         return {Iterator(_root,_root),true};
  165.                 }
  166.                 ValueOfk kot;
  167.                 Node* cur = _root;
  168.                 Node* parent = nullptr;
  169.                 while (cur)
  170.                 {
  171.                         //用键值k比较
  172.                         if (kot(cur->_data)< kot(data))
  173.                         {
  174.                                 parent = cur;
  175.                                 cur = cur->_right;
  176.                         }
  177.                         else if (kot(cur->_data) >kot(data))
  178.                         {
  179.                                 parent = cur;
  180.                                 cur =cur->_left;
  181.                         }
  182.                         else
  183.                         {
  184.                                 //return pair<Iterator,bool>({cur,_root},false);
  185.                                 return { Iterator(cur, _root), false };
  186.                         }
  187.                 }
  188.                 //插入
  189.                 cur = new Node(data);
  190.                 Node* newnode = cur;
  191.                 cur->_col = Red;
  192.                 if (kot(parent->_data) <kot(data))
  193.                         parent->_right = cur;
  194.                 else
  195.                         parent->_left = cur;
  196.                 cur->_parent = parent;
  197.                 //颜色处理+旋转
  198.                 while (parent&& parent->_col == Red)
  199.                 {
  200.                         Node* grandfather = parent->_parent;
  201.                         if (parent == grandfather->_left)
  202.                         {
  203.                                 //    g
  204.                                 //  p   u
  205.                                 Node* uncle = grandfather->_right;
  206.                                 //叔叔存在且为红
  207.                                 if (uncle && uncle->_col == Red)
  208.                                 {
  209.                                         //变色
  210.                                         parent->_col = Black;
  211.                                         uncle->_col = Black;
  212.                                         grandfather->_col = Red;
  213.                                         //继续向上处理
  214.                                         cur = grandfather;
  215.                                         parent = cur->_parent;
  216.                                 }
  217.                                 else
  218.                                 {
  219.                                         //叔叔不存在或者叔叔为黑
  220.                                         //    g
  221.                                     //  p   u
  222.                                    // c
  223.                                         //u为黑,则c是之前是黑的
  224.                                         //u不存在,则c是新插入的
  225.                                         if (cur == parent->_left)
  226.                                         {
  227.                                                 RotateR(grandfather);
  228.                                                 parent->_col = Black;
  229.                                                 grandfather->_col = Red;
  230.                                         }
  231.                                         else
  232.                                         {
  233.                                                 //    g
  234.                                                 //  p   u
  235.                                            //     c
  236.                                                 RotateL(parent);
  237.                                                 RotateR(grandfather);
  238.                                                 cur->_col = Black;
  239.                                                 grandfather->_col = Red;
  240.                                         }
  241.                                         break;
  242.                                 }
  243.                         }
  244.                         else
  245.                         {
  246.                                 //   g
  247.                                 // u   p
  248.                                 Node* uncle = grandfather->_left;
  249.                                 if (uncle && uncle->_col == Red)
  250.                                 {
  251.                                         //变色
  252.                                         parent->_col = Black;
  253.                                         uncle->_col = Black;
  254.                                         grandfather->_col = Red;
  255.                                         cur = grandfather;
  256.                                         parent = cur->_parent;
  257.                                 }
  258.                                 else
  259.                                 {
  260.                                         //   g
  261.                                     // u   p
  262.                                         //       c
  263.                                         if (cur == parent->_right)
  264.                                         {
  265.                                                 RotateL(grandfather);
  266.                                                 parent->_col = Black;
  267.                                                 grandfather->_col = Red;
  268.                                         }
  269.                                         else
  270.                                         {
  271.                                                 //   g
  272.                                             // u   p
  273.                                             //   c
  274.                                                 RotateR(parent);
  275.                                                 RotateL(grandfather);
  276.                                                 cur->_col = Black;
  277.                                                 grandfather->_col = Red;
  278.                                         }
  279.                                         break;
  280.                                 }
  281.                         }
  282.                 }
  283.                 _root->_col = Black;
  284.                 return pair<Iterator,bool>({newnode,_root},true);
  285.         }
  286.         void RotateR(Node* parent)
  287.         {
  288.                 Node* subL = parent->_left;
  289.                 Node* subLR = subL->_right;
  290.                 Node* pparent = parent->_parent;
  291.                 if (subLR)
  292.                         subLR->_parent = parent;
  293.                 parent->_left = subLR;
  294.                 subL->_right = parent;
  295.                 parent->_parent = subL;
  296.                 if (parent == _root)
  297.                 {
  298.                         _root = subL;
  299.                         _root->_parent = nullptr;
  300.                 }
  301.                 else
  302.                 {
  303.                         if (pparent->_left == parent)
  304.                                 pparent->_left = subL;
  305.                         else
  306.                                 pparent->_right = subL;
  307.                         subL->_parent = pparent;
  308.                 }
  309.         }
  310.         void RotateL(Node* parent)
  311.         {
  312.                 Node* subR = parent->_right;
  313.                 Node* subRL = subR->_left;
  314.                 Node* pparent = parent->_parent;
  315.                 parent->_right = subRL;
  316.                 if (subRL)
  317.                         subRL->_parent = parent;
  318.                 parent->_parent = subR;
  319.                 subR->_left = parent;
  320.                 if (parent == _root)
  321.                 {
  322.                         _root = subR;
  323.                         _root->_parent = nullptr;
  324.                 }
  325.                 else
  326.                 {
  327.                         if (pparent->_left == parent)
  328.                                 pparent->_left = subR;
  329.                         else
  330.                                 pparent->_right = subR;
  331.                         subR->_parent = pparent;
  332.                 }
  333.         }
  334.         void Inorder()
  335.         {
  336.                 _Inorder(_root);
  337.         }
  338.         int Height()
  339.         {
  340.                 return _Height(_root);
  341.         }
  342.         int size()
  343.         {
  344.                 return _size(_root);
  345.         }
  346.         int _size(Node* root)
  347.         {
  348.                 if (root == nullptr)
  349.                         return 0;
  350.                 return _size(root->_left) + _size(root->_right) + 1;
  351.         }
  352.         int _Height(Node* root)
  353.         {
  354.                 if (root == nullptr)
  355.                         return 0;
  356.                 int leftHeight = _Height(root->_left);
  357.                 int rightHeight = _Height(root->_right);
  358.                 return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
  359.         }
  360.         void _Inorder(Node* root)
  361.         {
  362.                 if (root == nullptr)
  363.                         return;
  364.                 _Inorder(root->_left);
  365.                 cout << root->_kv.first << ":" << root->_kv.second << endl;
  366.                 _Inorder(root->_right);
  367.         }
  368. private:
  369.         Node* _root=nullptr;
  370. };
复制代码
set.h
  1. #include "RBTree.h"
  2. //xg
  3. //key
  4. namespace xg
  5. {
  6.         template<class k>
  7.         class set
  8.         {
  9.         public:
  10.                 struct SetOfk
  11.                 {
  12.                         const k& operator()(const k& key)
  13.                         {
  14.                                 return key;
  15.                         }
  16.                 };
  17.                 typedef typename RBTree<k, const k, SetOfk>::Iterator iterator;
  18.                 typedef typename RBTree<k, const k, SetOfk>::ConstIterator const_iterator;
  19.                 iterator begin()
  20.                 {
  21.                         return _t.Begin();
  22.                 }
  23.                 iterator end()
  24.                 {
  25.                         return _t.End();
  26.                 }
  27.                 const_iterator begin()const
  28.                 {
  29.                         return _t.Begin();
  30.                 }
  31.                 const_iterator end() const
  32.                 {
  33.                         return _t.End();
  34.                 }
  35.                 pair<iterator,bool> insert(const k& key)
  36.                 {
  37.                         return _t.Insert(key);
  38.                 }
  39.         private:
  40.                 //底层调用红黑树
  41.                 RBTree<k, const k,SetOfk> _t;
  42.         };
  43. }
复制代码
map.h
  1. include "RBTree.h"
  2. //map
  3. //pair<k,v>
  4. namespace xg
  5. {
  6.         template<class k,class v>
  7.         class map
  8.         {
  9.         public:
  10.                 struct MapOfk
  11.                 {
  12.                         const k& operator()(const pair<k, v>& kv)
  13.                         {
  14.                                 return kv.first;
  15.                         }
  16.                 };
  17.                 typedef typename RBTree<k, pair<const k, v>, MapOfk>::Iterator iterator;
  18.                 typedef typename RBTree<k, pair<const k, v>, MapOfk>::ConstIterator const_iterator;
  19.                 iterator begin()
  20.                 {
  21.                         return _t.Begin();
  22.                 }
  23.                 iterator end()
  24.                 {
  25.                         return _t.End();
  26.                 }
  27.                 const_iterator begin() const
  28.                 {
  29.                         return _t.Begin();
  30.                 }
  31.                 const_iterator end() const
  32.                 {
  33.                         return _t.End();
  34.                 }
  35.                 pair<iterator,bool> insert(const pair<k, v>& kv)
  36.                 {
  37.                         return _t.Insert(kv);
  38.                 }
  39.                  v& operator[](const k& key)  
  40.                 {
  41.                         pair<iterator, bool> ret = insert({ key,v() });
  42.                         return ret.first->second;
  43.                 }
  44.         private:
  45.                 //底层调用红黑树
  46.                 RBTree<k, pair<const k, v>,MapOfk> _t;
  47.         };
  48. }
复制代码
2.6,代码测试

   #include "map.h"
#include "set.h"
#include <string>
  int main()
{   
    xg::set<int> s;
    s.insert(5);
    s.insert(1);
    s.insert(3);
    s.insert(2);
    s.insert(6);
      xg::set<int>::iterator sit = s.begin();
    
    while (sit != s.end())
    {   
        cout << *sit << " ";
        ++sit;
    }
    cout << endl;
      for (auto& e : s)
    {   
        cout << e << " ";
    }
    cout << endl;
      xg::map<string, string> dict;
    dict.insert({ "sort", "排序" });
    dict.insert({ "left", "左边" });
    dict.insert({ "right", "右边" });
      dict["left"] = "左边,剩余";
    dict["insert"] = "插入";
    dict["string"];
      xg::map<string, string>::iterator it = dict.begin();
    while (it!=dict.end())
    {   
        // 不能修改first,可以修改second
        //it->first += 'x';
        it->second += 'x';
          cout << it->first << ":" << it->second << endl;
        ++it;
    }
    cout << endl;
      for (auto& kv : dict)
    {   
        cout << kv.first << ":" << kv.second << endl;
    }
      return 0;
}
  
 


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

勿忘初心做自己

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表