封装红黑树实现Myset与Mymap
1. 源码及框架分析
SGI-STL30版本源代码,map和set的源代码在map/set/stl_map.h/stl_set.h/stl_tree.h等⼏个头⽂件中。
map和set的实现结构框架核⼼部分截取出来如下:
// set
#ifndef __SGI_STL_INTERNAL_TREE_H
#include <stl_tree.h>
#endif
#include <stl_set.h>
#include <stl_multiset.h>
// map
#ifndef __SGI_STL_INTERNAL_TREE_H
#include <stl_tree.h>
#endif
#include <stl_map.h>
#include <stl_multimap.h>
// stl_set.h
template <class Key, class Compare = less<Key>, class Alloc = alloc>
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
};
// stl_map.h
template <class Key, class T, class Compare = less<Key>, class Alloc = alloc>
class map {
public:
// typedefs:
typedef Key key_type;
typedef T mapped_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
};
// stl_tree.h
struct __rb_tree_node_base
{
typedef __rb_tree_color_type color_type;
typedef __rb_tree_node_base* base_ptr;
color_type color;
base_ptr parent;
base_ptr left;
base_ptr right;
};
// stl_tree.h
template <class Key, class Value, class KeyOfValue, class Compare, class Alloc
= alloc>
class rb_tree {
protected:
typedef void* void_pointer;
typedef __rb_tree_node_base* base_ptr;
typedef __rb_tree_node<Value> rb_tree_node;
typedef rb_tree_node* link_type;
typedef Key key_type;
typedef Value value_type;
public:
// insert⽤的是第⼆个模板参数左形参
pair<iterator,bool> insert_unique(const value_type& x);
// erase和find⽤第⼀个模板参数做形参
size_type erase(const key_type& x);
iterator find(const key_type& x);
protected:
size_type node_count; // keeps track of size of tree
link_type header;
};
template <class Value>
struct __rb_tree_node : public __rb_tree_node_base
{
typedef __rb_tree_node<Value>* link_type;
Value value_field;
};
• 通过下图对框架的分析,我们可以看到源码中rb_tree⽤了⼀个巧妙的泛型思想实现,rb_tree是实现key的搜索场景,还是key/value的搜索场景不是直接写死的,⽽是由第⼆个模板参数Value决定_rb_tree_node中存储的数据类型。
• 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反⽽是红⿊树结点中存储的真实的数据的类型。
• rb_tree第⼆个模板参数Value已经控制了红⿊树结点中存储的数据类型,为什么还要传第⼀个模板参数Key呢?尤其是set,两个模板参数是⼀样的,这是很多同学这时的⼀个疑问。要注意的是对于map和set,find/erase时的函数参数都是Key,所以第⼀个模板参数是传给find/erase等函数做形参的类型的。对于set⽽⾔两个参数是⼀样的,但是对于map⽽⾔就完全不⼀样了,map insert的是pair对象,但是find和ease的是Key对象。
• 吐槽⼀下,这⾥源码命名⻛格⽐较乱,set模板参数⽤的Key命名,map⽤的是Key和T命名,⽽
rb_tree⽤的⼜是Key和Value,可⻅⼤佬有时写代码也不规范,乱弹琴。
2. 模拟实现map和set
2.1 实现出复⽤红⿊树的框架,并⽀持insert
• 参考源码框架,map和set复⽤之前我们实现的红⿊树。
• 我们这⾥相⽐源码调整⼀下,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,再进⾏⽐较,具体细节参考如下代码实现。
// 源码中pair⽀持的<重载实现
template <class T1, class T2>
bool operator< (const pair<T1,T2>& lhs, const pair<T1,T2>& rhs)
{
return lhs.first<rhs.first || (!(rhs.first<lhs.first) &&
lhs.second<rhs.second); }
// Mymap.h
namespace bit
{
template<class K, class V>
class map
{
struct MapKeyOfT
{
const K& operator()(const pair<K, V>& kv)
{
return kv.first;
}
};
public:
bool insert(const pair<K, V>& kv)
{
return _t.Insert(kv);
}
private:
RBTree<K, pair<K, V>, MapKeyOfT> _t;
};
}
// Myset.h
namespace bit
{
template<class K>
class set
{
struct SetKeyOfT
{
const K& operator()(const K& key)
{
return key;
}
};
public:
bool insert(const K& key)
{
return _t.Insert(key);
}
private:
RBTree<K, K, SetKeyOfT> _t;
};
}
// RBTree.h
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)
{
}
};
// 实现步骤:
// 1、实现红⿊树
// 2、封装map和set框架,解决KeyOfT
// 3、iterator
// 4、const_iterator
// 5、key不⽀持修改的问题
// 6、operator[]
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的实现
iterator实现思路分析
• iterator实现的⼤框架跟list的iterator思路是⼀致的,⽤⼀个类型封装结点的指针,再通过重载运算符实现,迭代器像指针⼀样访问的⾏为。
• 这⾥的难点是operator++和operator–的实现。之前使⽤部分,我们分析了,map和set的迭代器⾛的是中序遍历,左⼦树->根结点->右⼦树,那么begin()会返回中序第⼀个结点的iterator也就是10所在结点的迭代器。
• 迭代器++的核⼼逻辑就是不看全局,只看局部,只考虑当前中序局部要访问的下⼀个结点。
• 迭代器++时,如果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,
const K, SetKeyOfT> _t;
• map的iterator不⽀持修改key但是可以修改value,我们把map的第⼆个模板参数pair的第⼀个参数改成const K即可, RBTree<K, pair<const K, V>, MapKeyOfT> _t;
• ⽀持完整的迭代器还有很多细节需要修改,具体参考下⾯题的代码。
2.3 map⽀持[]
• map要⽀持[]主要需要修改insert返回值⽀持,修改RBtree中的insert返回值为
pair<Iterator, bool> Insert(const T& data)
• 有了insert⽀持[]实现就很简单了,具体参考下⾯代码实现
2.4 bit::map和bit::set代码实现
RTree.h
#include<iostream>
#include<assert.h>
using namespace std;
enum Colour
{
Red,
Black
};
template<class T>
struct RBTreeNode
{
T _data;
Colour _col;
RBTreeNode<T>* _left;
RBTreeNode<T>* _right;
RBTreeNode<T>* _parent;
RBTreeNode(const T& data):
_data(data), _left(nullptr), _right(nullptr), _parent(nullptr), _col(Red)
{
}
};
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) {
}
Self operator++()
{
if (_node->_right)//父节点右不为空
{
Node* min = _node->_right;
while (min->_left)
{
min = min->_left;
}
_node = min;
}
else//父节点右为空
{
Node* cur = _node;
Node* parent = cur->_parent;
while (parent && cur == parent->_right)
{
cur = parent;
parent = cur->_parent;
}
_node = parent;
}
return *this;
}
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;
}
};
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* root = _root;
while (root->_left)
{
root = root->_left;
}
return Iterator(root);
}
Iterator end()
{
return Iterator(nullptr);
}
ConstIterator begin()const
{
Node* root = _root;
while (root->_left)
{
root = root->_left;
}
return ConstIterator(root);
}
ConstIterator end()const
{
return ConstIterator(nullptr);
}
pair<Iterator,bool> insert(const T& data)
{
if (_root == nullptr)
{
_root = new Node(data);
_root->_col = Black;
return {
Iterator(_root),true };
}
//空树
keyofT kot;
Node* parent = nullptr;
Node* cur = _root;
while (cur)
{
if (kot(data) < kot(cur->_data))
{
parent = cur;
cur = cur->_left;
}
else if (kot(data) > kot(cur->_data))
{
parent = cur;
cur = cur->_right;
}
else
{
return {
Iterator(cur),false };
}
}
//找到插入的位置
cur = new Node(data);
if (kot(cur->_data)<kot(parent->_data))
parent->_left = cur;
else
parent->_right = cur;
cur->_parent = parent;
//链接
while (parent && parent->_col == Red)
{
Node* pparent = parent->_parent;
if (parent == pparent->_left)//父亲在爷爷的左边
{
Node* uncle = pparent->_right;
if (uncle && uncle->_col == Red)
{
pparent->_col = Red;
parent->_col = Black;
uncle->_col = Black;
cur = pparent;
parent = cur->_parent;
}
else
{
if (cur == parent->_left)
{
RotateR(parent);
parent->_col = Black;
pparent->_col = Red;
}
else
{
RotateL(parent);
RotateR(pparent);
pparent->_col = Red;
parent->_col = Red;
cur->_col = Black;
}
}
}
else//父亲在爷爷的右边
{
Node* uncle = pparent->_left;
if (uncle && uncle->_col == Red)
{
pparent->_col = Red;
parent->_col = Black;
uncle->_col = Black;
cur = pparent;
parent = cur->_parent;
}
else
{
if (cur == parent->_left)
{
RotateR(parent);
RotateL(pparent);
pparent->_col = Red;
parent->_col = Red;
cur->_col = Black;
}
else
{
RotateL(parent);
pparent->_col = Red;
parent->_col = Black;
}
}
}
}
_root->_col = Black;
return {
Iterator(cur),true };
}
void RotateL(Node* parent)//左旋
{
Node* subR = parent->_right;
Node* subRL = subR->_left;
parent->_right = subRL;
if (subRL)
subRL->_parent = parent;
Node* pparent = parent->_parent;
parent->_parent = subR;
subR->_left = parent;
if (pparent == nullptr)
{
_root = subR;
subR->_parent = nullptr;
}
else
{
if (pparent->_left == parent)
{
pparent->_left = subR;
subR->_parent = pparent;
}
else
{
pparent->_right = subR;
subR->_parent = pparent;
}
}
}
void RotateR(Node* parent)//右旋
{
Node* subL = parent->_left;
Node* subLR = subL->_right;
parent->_left = subLR;
if (subLR)
subLR->_parent = parent;
Node* pparent = parent->_parent;
subL->_right = parent;
parent->_parent = subL;
if (pparent == nullptr)
{
_root = subL;
_root->_parent = nullptr;
}
else
{
if (pparent->_left == parent)
{
pparent->_left = subL;
subL->_parent = pparent;
}
else
{
pparent->_right = subL;
subL->_parent = pparent;
}
}
}
void inorder()
{
_inorder(_root);
}
private:
void _inorder(Node* root)
{
if (root == nullptr)
return;
_inorder(root->_left);
cout << root->_kv.first << ' ' << root->_kv.second << endl;
_inorder(root->_right);
}
Node* _root = nullptr;
};
Myset.h
#include"RBTree.h"
namespace tsy
{
template<class k>
class myset
{
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;
pair<iterator,bool> insert(const k& key)
{
return _t.insert(key);
}
iterator begin()
{
return _t.begin();
}
iterator end()
{
return _t.end();
}
const_iterator begin()const
{
return _t.begin();
}
const_iterator end()const
{
return _t.end();
}
private:
RBTree<k,const k, SetKeyofT> _t;
};
}
Mymap.h
namespace tsy
{
template<class k,class v>
class mymap
{
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;
pair<iterator, bool> insert(const pair<k,v>& kv)
{
return _t.insert(kv);
}
iterator begin()
{
return _t.begin();
}
iterator end()
{
return _t.end();
}
const_iterator begin()const
{
return _t.begin();
}
const_iterator end()const
{
return _t.end();
}
v& operator[](const k& key)
{
pair<iterator, bool> ret = insert({
key, v() });
return ret.first->second;
}
private:
RBTree<k, pair<const k,v>, MapKeyofT> _t;
};
}
test.c
#include"RBTree.h"
#include"MySet.h"
#include"MyMap.h"
//void test1()
//{
// RBTree<int, int> rbt;
// int arr[] = { 4,2,9,0,7,1,8 };
// for (auto & e: arr)
// {
// rbt.insert({ e,e });
// }
//
// rbt.inorder();
//}
void test2()
{
tsy::myset<int> st;
st.insert(1);
st.insert(0);
st.insert(9);
st.insert(2);
st.insert(5);
tsy::myset<int>::iterator it = st.begin();
while (it != st.end())
{
cout << *it << ' ';
++it;
}
}
void test3()
{
tsy::mymap<string, int> Map;
Map.insert({
"apple",3 });
Map.insert({
"banana",1 });
Map.insert({
"penapple",1 });
Map.insert({
"pear",0 });
tsy::mymap<string, int>::iterator it = Map.begin();
while (it != Map.end())
{
cout << it->first << ' ' << it->second << endl;
++it;
}
}
int main()
{
test3();
return 0;
}
2.5 迭代器–
这一部分我没有实现,所以这里set与map都不支持返向迭代器,如果要实现反向迭代器需要提供一个根节点的接口,这一块如果有想要代码的宝子可以找我私信。