1. 源码分析
- set实例化rb_tree时第二个模板参数给的是key,map实例化rb_tree时第⼆个模板参数给的是 pair<const key,T>,这样一颗红黑树既可以实现key搜索场景的set,也可以实现key/value搜索场 景的map
- 源码里面模板参数是用T代表value,而内部写的value_type不是日常 key/value场景中说的value,源码中的value_type反而是红黑树结点中存储的真实的数据的类型
- 为什么set要传两个key?因为对于 map和set,find/erase时的函数参数都是Key,第一个模板参数是传给find/erase等函数做形参的类型的。对于set两个参数是一样的,对于map不一样了,map的insert是pair对象,但是find和ease的是Key对象
2. 模拟实现map和set
2.1 复用红黑树的框架
- key参数就用K,value参数就用V,红黑树中的数据类型使用T
- 因为RBTree实现了泛型不知道T参数导致是K,还是pair<K,V>,那么insert内部进行插入逻辑比较时,就没办法进行比较,因为pair的默认支持的是key和value一起参与比较,我们需要时的任何时候只比较key,所以在map和set层分别实现一个MapKeyOfT和SetKeyOfT的仿函数传给RBTree的KeyOfT,然后RBTree中通过KeyOfT仿函数取出T类型对象中的key,再进行比较
//myset.h
namespace smc{template <class K>
class set
{struct SetKeyOfT {const K& operator()(const K& key){return key;}};
public:
private:RBTree<K,const K, SetKeyOfT> _rbtree;
};}
//mymap.h
namespace smc
{template<class K,class V>class map {struct MapKeyOfT{ const K& operator()(const pair<K, V>& kv){return kv.first;}};public:private:RBTree<K, pair<const K, V>, MapKeyOfT> _rbtree;};
}
// RBTree.h// 实现步骤:
// 1、实现红黑树
// 2、封装map和set框架,解决KeyOfT
// 3、iterator
// 4、const_iterator
// 5、key不支持修改的问题
// 6、operator[]
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){}
};
template<class K, class T, class KeyOfT>
class RBTree
{
private:typedef RBTreeNode<T> Node;Node* _root = nullptr;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;}
}
2.2 支持iterator的实现
- terator实现的框架跟list的iterator思路是一致的,用个类型封装结点的指针,再通过重载运算符实现,迭代器像指针一样访问的行为
- 这里的难点是operator++和operator--的实现。之前使⽤部分,map和set的迭代器走的是中序遍历,左子树->根结点->右子树,那么begin()会返回中序第一个结点的iterator也就是10所在结点的迭代器
- 迭代器++时,如果it指向的结点的右子树不为空,代表当前结点已经访问完了,要访问下一个结点 是右子树的中序第一个,一棵树中序第一个是最左结点,所以直接找右子树的最左结点即可
- 迭代器++时,如果it指向的结点的右子树为空,代表当前结点已经访问完了且当前结点所在的子树也访问完了,要往上走。而且如果当前it是其父节点的右子树,表示这整个子树都完了,就要去找it的祖先节点
- 如果当前结点是父亲的左,根据中序左子树->根结点->右子树,那么下一个访问的结点就是当前结 点的父亲;如下图:it指向25,25右为空,25是30的左,所以下一个访问的结点就是30
- 如果当前结点是父亲的右,根据中序左子树->根结点->右子树,当前当前结点所在的子树访问完 了,当前结点所在父亲的子树也访问完了,那么下一个访问的需要继续往根的祖先中去找,直到找 到孩⼦是父亲左的那个祖先就是中序要问题的下一个结点。如下图:it指向15,15右为空,15是10 的右,15所在子树话访问完了,10所在子树也访问完了,继续往上找,10是18的左,那么下一个 访问的结点就是18
- end()如何表示?如下图:当it指向50时,++it时,50是40的右,40是30的右,30是18的右,18 到根没有父亲,没有找到孩⼦是父亲左的那个祖先,这是父亲为空了,那我们就把it中的结点指针置为nullptr,用nullptr去充当end。需要注意的是stl源码空,红黑树增加了一个哨兵位头结点 做为end(),这哨兵位头结点和根互为父亲,左指向最左结点,右指向最右结点。相比我们用 nullptr作为end(),只是--end()判断到结点时空,特殊处理一下,让迭代器结点指向最右结点。具体参考迭代器--实现
- 迭代器--的实现跟++的思路完全类似,逻辑正好反过来即可,访问顺序是右子树->根结点-> 左子树
- set的iterator也不支持修改,我们把set的第⼆个模板参数改成const K即可, 即RBTree<K,pair<K,V>,SetKeyOfT> _rbtree
- map的iterator不支持修改key但是可以修改value,我们把map的第二个模板参数pair的第一个参数改成const K即可,即RBTree<K, pair<const K, V>, MapKeyOfT> _rbtree;
2.3 map支持[ ]
map要支持[ ]主要需要修改insert返回值支持,修改RBtree中的insert返回值为
pair<Iterator,bool> Insert(const T& data)
2.4 smc::set和smc::map代码实现
dwaekkiyo/test - Gitee.com
//set.h
namespace smc
{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 _rbtree.begin();}iterator end(){return _rbtree.end();}const_iterator begin() const{return _rbtree.begin();}const_iterator end() const{return _rbtree.end();}pair<iterator,bool> insert(const K& key){return _rbtree.Insert(key);}iterator Find(const K& key){_rbtree.Find(key);}private:RBTree<K,const K, SetKeyOfT> _rbtree;};
}
//map.h
namespace smc
{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 _rbtree.begin();}iterator end(){return _rbtree.end();}const_iterator begin() const{return _rbtree.Begin();}const_iterator end() const{return _rbtree.End();}pair<iterator,bool> insert(const pair<K,V> kv){return _rbtree.Insert(kv);}V& operator[](const K& key){pair<iterator, bool> ret = _rbtree.Insert({ key,V() });return ret.first->second;}iterator Find(const K& key){_rbtree.Find(key);}private:RBTree<K, pair<const K, V>, MapKeyOfT> _rbtree;};void test_map(){map<string, string> dict;dict.insert({ "sort", "排序" });dict.insert({ "left", "左边" });dict.insert({ "right", "右边" });dict["left"] = "左边,剩余";dict["insert"] = "插入";dict["string"];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;}
}
//RBTree.h
#pragma onceenum 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){}
};template <class T,class Ref,class Ptr>
struct RBTreeIterator
{typedef RBTreeNode<T> Node;typedef RBTreeIterator<T,Ref,Ptr> Self;Node* _node;Node* _root;RBTreeIterator(Node* node,Node* root):_node(node),_root(root){}Self& operator++(){if (_node->_right){Node* minleft = _node->_right;while (minleft->_left){minleft = minleft->_left;}_node = minleft;}else{Node* cur = _node;Node* parent = cur->_parent;while (parent && cur == parent->_right){cur = parent;parent = parent->_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 = parent->_parent;}_node = parent;}return *this;}Ref operator*() {return _node->_data;}Ptr operator->(){return &(_node->_data);}bool operator!=(const Self& s){return _node != s._node;}bool operator==(const Self& s){return _node == s._node;}};template<class K, class T,class KeyOfT>
class RBTree
{typedef RBTreeNode<T> Node;public:typedef RBTreeIterator<T,T&,T*> Iterator;typedef RBTreeIterator<T,const T&,const T*> ConstIterator;Iterator begin(){Node* cur = _root;while (cur&& cur->_left){cur = cur->_left;}return Iterator(cur,_root);}Iterator end(){return Iterator(nullptr,_root);}ConstIterator begin() const{Node* cur = _root;while (cur && cur->_left){cur = cur->_left;}return ConstIterator(cur, _root);}ConstIterator end() const{return ConstIterator(nullptr, _root);}pair<Iterator,bool> Insert(const T& data){if (_root == nullptr){_root = new Node(data);_root->_col = Black;return make_pair(Iterator(_root,_root),true);}Node* cur = _root;Node* parent = nullptr;KeyOfT kot;while (cur){if (kot(cur->_data) > kot(data)){parent = cur;cur = cur->_left;}else if (kot(cur->_data) < kot(data)){parent = cur;cur = cur->_right;}else{return make_pair(Iterator(cur,_root),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* grandfather = parent->_parent;if (parent == grandfather->_left){// g// p u//Node* uncle = grandfather->_right;//u存在且为红if (uncle && uncle->_col == Red){//变色parent->_col = Black;uncle->_col = Black;grandfather->_col = Red;//继续向上处理cur = grandfather;parent = cur->_parent;}else{//uncle不存在,或者存在且为黑if (cur == parent->_left){// 旋转+变色// g// p u//cRotateR(grandfather);parent->_col = Black;grandfather->_col = Red;}else{// 双旋转+变色// g// p u// cRotateL(parent);RotateR(grandfather);cur->_col = Black;//cur做了这棵树的根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//uncle不存在,或者存在且为黑{// 旋转+变色// g// u p// cif (cur == parent->_right){RotateL(grandfather);parent->_col = Black;grandfather->_col = Red;}else{// 双旋转+变色// g// u p// cRotateR(parent);RotateL(grandfather);cur->_col = Black;grandfather->_col = Red;}break;}}}_root->_col = Black;//不返回cur是因为旋转后cur可能已经不在原位//所以newnode记录新节点并返回//return make_pair(Iterator(cur,_root),true);return make_pair(Iterator(newnode,_root),true);}bool Check(Node* root, int BlackNum, const int refNum){// blackNum 根到当前结点的黑结点的数量if (root == nullptr){// 前序遍历走到空时,意味着一条路径走完了if (BlackNum != refNum){cout << "存在黑色结点的数量不相等的路径" << endl;return false;}return true;}//检查父亲if (root->_col == Red && root->_parent->_col == Red){cout << root->_kv.first << "存在连续的红结点" << endl;return false;}if (root->_col == Black){BlackNum++;}return Check(root->_left, BlackNum, refNum) && Check(root->_right, BlackNum, refNum);}bool IsBalance(){if (_root == nullptr){return true;}if (_root->_col == Red){return false;}Node* cur = _root;int refNum = 0; // 参考值 while (cur){if (cur->_col == Black)++refNum;cur = cur->_left;}return Check(_root, 0, refNum);}Iterator Find(const K& key){Node* cur = _root;while (cur){if (cur->_kv.first < key){cur = cur->_right;}else if (cur->_kv.first > key){cur = cur->_left;}else{return Iterator(cur,_root);}}return end();}void InOrder(){_InOrder(_root);cout << endl;}int Height(){return _Height(_root);}int Size(){return _Size(_root);}protected:int _Size(Node* root){if (root == nullptr)return 0;return _Size(root->_left) + _Size(root->_right) + 1;}int _Height(Node* root){if (root == nullptr)return 0;int leftHeight = _Height(root->_left);int rightHeight = _Height(root->_right);return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;}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 (ppNode == nullptr)if (parent == _root){_root = subL;subL->_parent = nullptr;}else{if (ppNode->_left == parent){ppNode->_left = subL;}else{ppNode->_right = subL;}subL->_parent = ppNode;}}void RotateL(Node* parent){Node* subR = parent->_right;Node* subRL = subR->_left;parent->_right = subRL;if (subRL)subRL->_parent = parent;Node* parentParent = parent->_parent;subR->_left = parent;parent->_parent = subR;if (parentParent == nullptr){_root = subR;subR->_parent = nullptr;}else{if (parent == parentParent->_left){parentParent->_left = subR;}else{parentParent->_right = subR;}subR->_parent = parentParent;}}void _InOrder(Node* root){if (root == nullptr){return;}_InOrder(root->_left);cout << root->_kv.first << ":" << root->_kv.second << endl;_InOrder(root->_right);}
private:Node* _root = nullptr;
};