【C++】使用红黑树封装map和set
文章目录
- 前言
- 一. 源码及框架分析
- 二. 模拟实现map和set
- 2.1 复用红黑树框架并实现insert
- 2.2 支持iterator的实现
- 2.2.1 基本的运算符重载
- 2.2.2
operator++
的重载 - 2.2.3
operator--
的重载 - 2.2.4 RBTree、set和map的迭代器实现
- 三. map的operator[]的实现
- 四. set和map的erase函数(可选)
- 五. map和set的构造函数和析构函数
- 最后
前言
在上一篇文章中,我们详细介绍了红黑树的实现,内容很重要,请大家务必掌握!那么本篇文章将带大家详细讲解红黑树封装map和set的实现,接下来一起看看吧!
一. 源码及框架分析
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 treelink_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和erase的是Key对象
。
二. 模拟实现map和set
2.1 复用红黑树框架并实现insert
红黑树的模板参数至少要用到三个:
template<class K, class T, class KeyOfT>
K表示存储的Key值,T表示实际存储的数据类型,KeyOfT的作用是什么?
首先insert的是T类型,但是我们并不知道T是Key还是pair<const K,V>,那么该如何比较大小呢?
看一下pair对象的比较方法是什么:
可以看到库里面的pair
比较大小的方法是first
大就大,first
小就小,first
相等则比较second
。
但是我们不需要这样的比较方式,我们就想比较first(Key)
,first
相等就相等。
这个时候KeyOfT就派上用场了:
KeyOfT
是一个仿函数
,通过重载operator()
方法获得T中的K
如果T
是K
则返回K
,如果T
是pair<K,V>
则返回K
我们只需要在set和map类中实现一个内部类MapKeyOfT
和SetKeyOfT
,再直接传过去给红黑树的第三个模板参数就可以了,这样RBTree就可以拿到T中的K。
实现insert
RBTree.h
// 枚举值表示颜色
enum Color
{RED,BLACK
};
// T存储实际存储的数据类型
template<class T>
struct RBTreeNode
{// 这里更新控制平衡也要加入parent指针T _kv;RBTreeNode<T>* _left;RBTreeNode<T>* _right;RBTreeNode<T>* _parent;Color _col;RBTreeNode(const T& kv):_kv(kv),_left(nullptr),_right(nullptr),_parent(nullptr),_col(RED){}
};
template<class K, class T, class KeyOfT>
class RBTree
{KeyOfT kot;
public:typedef RBTreeNode<T> Node;bool Insert(const pair<K, V>& kv){if (_root == nullptr) {_root = new Node(kv);_root->_col = BLACK;return true;}Node* cur = _root;Node* parent = nullptr;while (cur){if (kv.first > cur->_kv.first) {parent = cur;cur = cur->_right;}else if (kv.first < cur->_kv.first) {parent = cur;cur = cur->_left;}else {return false;}}cur = new Node(kv);// 新增节点,颜色红色cur->_col = RED;cur->_parent = parent;if (kv.first > parent->_kv.first) {parent->_right = cur;}else {parent->_left = cur;}//对不满足规则的情况进行调整while (parent && parent->_col == RED){Node* grandfather = parent->_parent;// g// p uif (grandfather->_left == parent) {Node* uncle = grandfather->_right;if (uncle && uncle->_col == RED) {// 叔叔存在且为红,变色再继续往上处理parent->_col = BLACK;uncle->_col = BLACK;grandfather->_col = RED;cur = grandfather;parent = cur->_parent;}else {// 叔叔不存在或存在且为黑,旋转+变色if (parent->_left == cur) {// g// p u//c//单旋RotateR(grandfather);grandfather->_col = RED;parent->_col = BLACK;}else {// g// p u// c//双旋RotateL(parent);RotateR(grandfather);grandfather->_col = RED;cur->_col = BLACK;}break;}}else {Node* uncle = grandfather->_left;if (uncle && uncle->_col == RED) {// 叔叔存在且为红,变色再继续往上处理parent->_col = BLACK;uncle->_col = BLACK;grandfather->_col = RED;cur = grandfather;parent = cur->_parent;}else {// 叔叔不存在或存在且为黑,旋转+变色if (parent->_right == cur) {// g// u p// c// 单旋RotateL(grandfather);grandfather->_col = RED;parent->_col = BLACK;}else {// g// u p// c// 双旋RotateR(parent);RotateL(grandfather);grandfather->_col = RED;cur->_col = BLACK;}break;}}}_root->_col = BLACK;return true;}
private:// 右单旋void RotateR(Node* parent){Node* subL = parent->_left;Node* subLR = subL->_right;subL->_right = parent;parent->_left = subLR;if (subLR)subLR->_parent = parent;Node* parentParent = parent->_parent;parent->_parent = subL;if (parentParent == nullptr) {// 如果parent为根节点则更新根节点_root = subL;subL->_parent = nullptr;}else {// subL和parentParent建立联系if (parentParent->_left == parent) {parentParent->_left = subL;}else {parentParent->_right = subL;}subL->_parent = parentParent;}}//左单旋void RotateL(Node* parent){Node* subR = parent->_right;Node* subRL = subR->_left;subR->_left = parent;parent->_right = subRL;if (subRL)subRL->_parent = parent;Node* parentParent = parent->_parent;parent->_parent = subR;if (parentParent == nullptr) {// 如果parent为根节点则更新根节点_root = subR;subR->_parent = nullptr;}else {// subR和parentParent建立联系if (parentParent->_left == parent) {parentParent->_left = subR;}else {parentParent->_right = subR;}subR->_parent = parentParent;}}
private:Node* _root = nullptr;
};
mymap.h
map的iterator不支持修改key但是可以修改value,我们把map的第二个模板参数pair的第一个参
数改成const K即可, RBTree<K, pair<const K, V>, MapKeyOfT> _rbtree;
namespace MyMap
{template<class K, class V>class map{struct MapKeyOfT{const K& operator()(const pair<K, V>& kv){return kv.first;}};public:map() = default;bool insert(const pair<const K, V>& kv){return _rbtree.Insert(kv);}private:RBTree<K, pair<const K, V>, MapKeyOfT> _rbtree;};
}
myset.h
set的iterator也不支持修改,我们把set的第二个模板参数改成const K即可, RBTree<K, const K, SetKeyOfT> _rbtree;
namespace MySet
{template<class K>class set{struct SetKeyOfT {const K& operator()(const K& key){return key;}};public:set() = default;bool insert(const K& kv){return _rbtree.Insert(kv);}private:RBTree<K, const K, SetKeyOfT> _rbtree;};
}
2.2 支持iterator的实现
iterator的核心源码:
struct __rb_tree_base_iterator
{typedef __rb_tree_node_base::base_ptr base_ptr;base_ptr node;void increment(){if (node->right != 0) {node = node->right;while (node->left != 0)node = node->left;}else {base_ptr y = node->parent;while (node == y->right) {node = y;y = y->parent;}if (node->right != y)node = y;}}void decrement(){if (node->color == __rb_tree_red &&node->parent->parent == node)node = node->right;else if (node->left != 0) {base_ptr y = node->left;while (y->right != 0)y = y->right;node = y;}else {base_ptr y = node->parent;while (node == y->left) {node = y;y = y->parent;}node = y;}}
};
template <class Value, class Ref, class Ptr>
struct __rb_tree_iterator : public __rb_tree_base_iterator
{typedef Value value_type;typedef Ref reference;typedef Ptr pointer;typedef __rb_tree_iterator<Value, Value&, Value*> iterator;__rb_tree_iterator() {}__rb_tree_iterator(link_type x) { node = x; }__rb_tree_iterator(const iterator& it) { node = it.node; }reference operator*() const { return link_type(node)->value_field; }
#ifndef __SGI_STL_NO_ARROW_OPERATORpointer operator->() const { return &(operator*()); }
#endif /* __SGI_STL_NO_ARROW_OPERATOR */self& operator++() { increment(); return *this; }self& operator--() { decrement(); return *this; }inline bool operator==(const __rb_tree_base_iterator& x,const __rb_tree_base_iterator& y) {return x.node == y.node;}inline bool operator!=(const __rb_tree_base_iterator& x,const __rb_tree_base_iterator& y) {return x.node != y.node;}
}
iterator实现的大框架跟list的iterator思路是一致的,用一个类型封装结点的指针,再通过重载运算符实现,迭代器像指针一样访问的行为。
2.2.1 基本的运算符重载
template<class T, class Ref, class Ptr>
struct RBTreeIterator
{typedef RBTreeNode<T> Node;typedef RBTreeIterator<T, Ref, Ptr> Self;RBTreeIterator(Node* node):_node(node),{}Ref operator*(){return _node->_kv;}Ptr operator->(){return &_node->_kv;}bool operator!=(const Self& it) const{return _node != it._node;}bool operator==(const Self& it) const{return _node == it._node;}Node* _node;
};
2.2.2 operator++
的重载
这里的难点是operator++和operator–的实现。之前使用部分,我们分析了,map和set的迭代器走的是中序遍历
:左子树->根结点->右子树
。那么begin()
会返回中序第一个节点所在位置的迭代器。
如果遍历到当前节点的时候,要继续访问下一个节点应当去访问它的右子树,因为当前节点的左子树肯定遍历完了才会遍历到当前节点。
- 如果当前节点的右子树不为空,代表当前节点的左子树访问完了,要访问下一个节点是右子树的中序第一个,一棵树中序第一个是最左节点,也就是右子树的最左节点。
- 如果当前节点的右子树为空,代表当前节点已经访问完了且当前节点所在的子树也访问完了,要访问的下一个节点在当前节点的祖先里面,所以要沿着当前节点到根的祖先路径向上找。
- 如何找?根据
中序遍历
:左子树->根结点->右子树
这个访问顺序就可以发现:如果当前节点是它父亲节点的左孩子,说明父亲节点的左子树访问完了,下一个访问的节点就是父亲节点
;如果当前节点是它父亲节点的右孩子,那么父亲节点的右子树访问完了,说明以父节点为根的子树也访问完了,那么下一个访问的节点需要继续往根的祖先中去找,直到找到孩子是父亲左的那个祖先就是下一个节点
。
代码实现:
Self& operator++()
{if (_node->_right){Node* cur = _node->_right;while (cur->_left){cur = cur->_left;}_node = cur;}else{Node* cur = _node;Node* parent = _node->_parent;while (parent && parent->_right == cur){cur = parent;parent = parent->_parent;}_node = parent;}return *this;
}
2.2.3 operator–
的重载
迭代器–的实现跟++的思路完全类似,逻辑正好反过来即可,因为他访问顺序是右子树->根结点->左子树
。
- 当使用迭代器遍历红黑树的节点时,如果遇到
nullptr
,我们就用nullptr去充当end()
,当–end()
判断到节点为空时,还需要特殊处理一下:让迭代器节点指针指向红黑树的最右节点(中序的最后一个)- 那么怎么找到最右节点?(源码使用一个哨兵位节点去充当end(),让哨兵位节点的右孩子指向最右节点,这样就可以找到了)我们这里让迭代器类增加一个成员去存储红黑树的根节点即可,通过根节点就可以找到最右节点。
代码实现:
Self& operator--()
{if (_node == nullptr){Node* cur = _root;while (cur && cur->_right){cur = cur->_right;}_node = cur;}else if (_node->_left){Node* cur = _node->_left;while (cur->_right){cur = cur->_right;}_node = cur;}else{Node* cur = _node;Node* parent = _node->_parent;while (parent && parent->_left == cur){cur = parent;parent = parent->_parent;}_node = parent;}return *this;
}
上面的前置++和前置–已经实现了,那么后置++和后置–就很简单了,下面看完整代码:
template<class T, class Ref, class Ptr>
struct RBTreeIterator
{typedef RBTreeNode<T> Node;typedef RBTreeIterator<T, Ref, Ptr> Self;RBTreeIterator(Node* node, Node* root):_node(node),_root(root){}Ref operator*(){return _node->_kv;}Ptr operator->(){return &_node->_kv;}bool operator!=(const Self& it) const{return _node != it._node;}bool operator==(const Self& it) const{return _node == it._node;}// 前置++Self& operator++(){if (_node->_right){Node* cur = _node->_right;while (cur->_left){cur = cur->_left;}_node = cur;}else{Node* cur = _node;Node* parent = _node->_parent;while (parent && parent->_right == cur){cur = parent;parent = parent->_parent;}_node = parent;}return *this;}// 前置--Self& operator--(){if (_node == nullptr){Node* cur = _root;while (cur && cur->_right){cur = cur->_right;}_node = cur;}else if (_node->_left){Node* cur = _node->_left;while (cur->_right){cur = cur->_right;}_node = cur;}else{Node* cur = _node;Node* parent = _node->_parent;while (parent && parent->_left == cur){cur = parent;parent = parent->_parent;}_node = parent;}return *this;}// 后置++Self operator++(int){Self tmp = *this;++(*this);return tmp;}// 后置--Self operator--(int){Self tmp = *this;--(*this);return tmp;}Node* _node;Node* _root;
};
2.2.4 RBTree、set和map的迭代器实现
RBTree
这里begin()返回的是中序遍历的第一个节点的位置,也就是红黑树的最左节点;而end()返回的则是nullptr的位置
typedef RBTreeIterator<T, T&, T*> Iterator;
typedef RBTreeIterator<T, const T&, const T*> ConstIterator;
Iterator Begin()
{Node* cur = _root;while (cur->_left){cur = cur->_left;}return Iterator(cur, _root);
}
Iterator End()
{return Iterator(nullptr, _root);
}
ConstIterator Begin() const
{Node* cur = _root;while (cur->_left){cur = cur->_left;}return ConstIterator(cur, _root);
}
ConstIterator End() const
{return ConstIterator(nullptr, _root);
}
set
和map
直接对RBTree的迭代器进行复用即可。
set
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();
}
map
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();
}
这里的
typedef typename RBTree<K, pair<const K, V>, MapKeyOfT>::Iterator iterator;
中的typename
是告诉编译器这是个类型,因为编译器不知道Iterator
是类型还是成员变量(因为编译器是按需实例化的),加了typename
是明确告诉编译器这是个类型。
测试:
#include "mymap.h"
#include "myset.h"
void test_set()
{MySet::set<int> st;st.insert(1);st.insert(6);st.insert(3);st.insert(8);MySet::set<int>::iterator it = st.begin();while (it != st.end()){cout << *it << " ";++it;}cout << endl;
}
void test_map()
{MyMap::map<int, int> mp;mp.insert({ 4,40 });mp.insert({ 2,20 });mp.insert({ 1,10 });mp.insert({ 3,30 });MyMap::map<int, int>::iterator it = mp.begin();while (it != mp.end()){cout << it->first << " " << it->second << endl;++it;}cout << endl;
}
int main()
{test_set();test_map();return 0;
}
三. map的operator[]的实现
map
的operator[]
,我们知道它有两种功能:
查找+修改
:key存在,返回value的引用插入+修改
:key不存在,插入key和value的缺省值,返回value的引用
看一下map库里面的insert函数:
库里面返回的是pair<iterator , bool>
类型,说明:
- 如果
key
存在,则返回该节点的迭代器
和false
。- 如果
key
不存在,则返回新插入节点的迭代器
和true
。
修改后的插入函数(RBTree):
pair<Iterator, bool> Insert(const T& kv)
{if (_root == nullptr) {_root = new Node(kv);_root->_col = BLACK;return make_pair(Iterator(_root, _root), true);}Node* cur = _root;Node* parent = nullptr;while (cur){if (kot(kv) > kot(cur->_kv)) {parent = cur;cur = cur->_right;}else if (kot(kv) < kot(cur->_kv)) {parent = cur;cur = cur->_left;}else {return make_pair(Iterator(cur, _root), false);}}cur = new Node(kv);Node* newnode = cur;// 新增节点,颜色红色cur->_col = RED;cur->_parent = parent;if (kot(kv) > kot(parent->_kv)) {parent->_right = cur;}else {parent->_left = cur;}while (parent && parent->_col == RED){Node* grandfather = parent->_parent;// g// p uif (grandfather->_left == parent) {Node* uncle = grandfather->_right;if (uncle && uncle->_col == RED) {// 叔叔存在且为红,变色再继续往上处理parent->_col = BLACK;uncle->_col = BLACK;grandfather->_col = RED;cur = grandfather;parent = cur->_parent;}else {// 叔叔不存在或存在且为黑,旋转+变色if (parent->_left == cur) {// g// p u//c//单旋RotateR(grandfather);grandfather->_col = RED;parent->_col = BLACK;}else {// g// p u// c//双旋RotateL(parent);RotateR(grandfather);grandfather->_col = RED;cur->_col = BLACK;}break;}}else {Node* uncle = grandfather->_left;if (uncle && uncle->_col == RED) {// 叔叔存在且为红,变色再继续往上处理parent->_col = BLACK;uncle->_col = BLACK;grandfather->_col = RED;cur = grandfather;parent = cur->_parent;}else {// 叔叔不存在或存在且为黑,旋转+变色if (parent->_right == cur) {// g// u p// c// 单旋RotateL(grandfather);grandfather->_col = RED;parent->_col = BLACK;}else {// g// u p// c// 双旋RotateR(parent);RotateL(grandfather);grandfather->_col = RED;cur->_col = BLACK;}break;}}}_root->_col = BLACK;return make_pair(Iterator(newnode, _root), true);
}
map
实现operator[]
:
pair<iterator, bool> insert(const pair<K, V>& kv)
{return _rbtree.Insert(kv);
}
V& operator[](const K& key)
{pair<iterator, bool> ret = insert(make_pair(key, V()));return ret.first->second;
}
测试:
void test_map()
{MyMap::map<string, string> dict;dict.insert({ "sort", "排序" });dict.insert({ "left", "左边" });dict.insert({ "right", "右边" });dict["left"] = "左边,剩余";dict["insert"] = "插入";dict["string"];MyMap::map<string, string>::iterator it = dict.begin();while (it != dict.end()){it->second += 's';cout << it->first << ":" << it->second << endl;++it;}cout << endl;
}
四. set和map的erase函数(可选)
RBTree
的erase比较难,感兴趣的可以看看:
// 删除
bool Erase(const K& key)
{if (_root == nullptr) return false;/*Node* cur = _root;Node* parent = nullptr;while (cur){if (key > kot(cur->_kv)) {parent = cur;cur = cur->_right;}else if (key < kot(cur->_kv)) {parent = cur;cur = cur->_left;}else {break;}}if (cur == nullptr) return false;*/Node* cur = Find(key)._node;if (cur == nullptr) {return false;}Node* parent = cur->_parent;if (cur->_left && cur->_right){Node* minRight = cur->_right;Node* minRightParent = cur;while (minRight->_left){minRightParent = minRight;minRight = minRight->_left;}// cur->_kv = minRight->_kv;// 用新节点代替cur,解决不能直接代替值的问题Node* ReplaceNode = new Node(minRight->_kv);ReplaceNode->_col = cur->_col;ReplaceNode->_left = cur->_left;ReplaceNode->_right = cur->_right;ReplaceNode->_parent = cur->_parent;if (ReplaceNode->_left) ReplaceNode->_left->_parent = ReplaceNode;if (ReplaceNode->_right) ReplaceNode->_right->_parent = ReplaceNode;if (cur->_parent) {if (cur->_parent->_left == cur) {cur->_parent->_left = ReplaceNode;}else {cur->_parent->_right = ReplaceNode;}}else {_root = ReplaceNode;}if (minRightParent == cur){// 细节:如果minRightParent指向cur,需要将minRightParent指向ReplaceNodeminRightParent = ReplaceNode;}// 删除原节点delete cur;cur = minRight;parent = minRightParent;}Node* child = nullptr;if (cur->_left) child = cur->_left;else child = cur->_right;if (child) child->_parent = parent;if (parent == nullptr) {_root = child;if (_root) _root->_col = BLACK;delete cur;return true;}if (child) {if (parent->_left == cur) {parent->_left = child;}else {parent->_right = child;}child->_col = BLACK;}else {Node* pNode = cur;if (pNode->_col == RED) {if (parent->_left == cur) {parent->_left = nullptr;}else {parent->_right = nullptr;}delete cur;return true;}// pNode表示双黑节点while (pNode){if (pNode->_col == RED || pNode == _root){pNode->_col = BLACK;break;}Node* bro = nullptr;if (parent->_left == pNode){bro = parent->_right;if (bro->_col == BLACK){Node* broR = bro->_right;Node* broL = bro->_left;if (broR && broR->_col == RED){broR->_col = bro->_col;bro->_col = parent->_col;parent->_col = BLACK;RotateL(parent);break;}else if (broL && broL->_col == RED){broL->_col = parent->_col;parent->_col = BLACK;RotateR(bro);RotateL(parent);break;}else{bro->_col = RED;pNode = parent;parent = parent->_parent;}}else{bro->_col = BLACK;parent->_col = RED;RotateL(parent);}}else{bro = parent->_left;if (bro->_col == BLACK){Node* broR = bro->_right;Node* broL = bro->_left;if (broL && broL->_col == RED){broL->_col = bro->_col;bro->_col = parent->_col;parent->_col = BLACK;RotateR(parent);break;}else if (broR && broR->_col == RED){broR->_col = parent->_col;parent->_col = BLACK;RotateL(bro);RotateR(parent);break;}else{bro->_col = RED;pNode = parent;parent = parent->_parent;}}else{bro->_col = BLACK;parent->_col = RED;RotateR(parent);}}}parent = cur->_parent;if (parent->_left == cur) {parent->_left = nullptr;}else {parent->_right = nullptr;}delete cur;}_root->_col = BLACK;return true;
}
这里代替节点时不能简单地使用cur->_kv = minRight->_kv;
了,因为key是不能修改的,我们可以再开辟一个新节点代替cur的位置,再删除cur节点,再让cur指向要被删除的节点即可。
代码实现:
set
和map
void erase(const K& key)
{_rbtree.Erase(key);
}
测试:
void test_set()
{MySet::set<int> st;st.insert(1);st.insert(6);st.insert(3);st.insert(8);MySet::set<int>::iterator it = st.begin();while (it != st.end()){cout << *it << " ";++it;}cout << endl;st.erase(3);it = st.begin();while (it != st.end()){cout << *it << " ";++it;}cout << endl;st.erase(8);it = st.begin();while (it != st.end()){cout << *it << " ";++it;}cout << endl;
}
void test_map()
{MyMap::map<string, string> dict;dict.insert({ "sort", "排序" });dict.insert({ "left", "左边" });dict.insert({ "right", "右边" });dict["left"] = "左边,剩余";dict["insert"] = "插入";dict["string"];MyMap::map<string, string>::iterator it = dict.begin();while (it != dict.end()){it->second += 's';cout << it->first << ":" << it->second << endl;++it;}cout << endl;dict.erase("insert");auto it1 = dict.begin();while (it1 != dict.end()){cout << it1->first << ":" << it1->second << endl;++it1;}cout << endl;dict.erase("string");it1 = dict.begin();while (it1 != dict.end()){cout << it1->first << ":" << it1->second << endl;++it1;}cout << endl;
}
int main()
{test_set();test_map();return 0;
}
五. map和set的构造函数和析构函数
RBTree
的构造函数和析构函数:
RBTree() = default;
~RBTree()
{Destory(_root);
}
RBTree(const Self& rbtree)
{_root = NodeCopy(rbtree._root, nullptr);
}
Self& operator=(const Self& rbtree)
{_root = NodeCopy(rbtree._root, nullptr);return *this;
}
void Destory(Node* root)
{if (root == nullptr) return;if (root->_left) Destory(root->_left);if (root->_right) Destory(root->_right);delete root;root = nullptr;
}Node* NodeCopy(Node* root, Node* parent)
{if (root == nullptr) return nullptr;Node* newnode = new Node(root->_kv);newnode->_col = root->_col;newnode->_parent = parent;newnode->_left = NodeCopy(root->_left, newnode);newnode->_right = NodeCopy(root->_right, newnode);return newnode;
}
set
的构造函数和析构函数:
set() = default;
set(initializer_list<K> il)
{for (const auto& e : il){_rbtree.Insert(e);}
}
template<class InputIterator>
set(InputIterator first, InputIterator last)
{while (first != last){_rbtree.Insert(*first);++first;}
}
set(const set& x)
{//_rbtree = x._rbtree;for (const auto& e : x){_rbtree.Insert(e);}
}
set& operator=(const set& x)
{_rbtree = x._rbtree;return *this;
}
map
的构造函数和析构函数:
map() = default;
map(initializer_list<pair<K, V>> il)
{for (const auto& e : il){_rbtree.Insert(e);}
}
template<class InputIterator>
map(InputIterator first, InputIterator last)
{while (first != last){_rbtree.Insert(*first);++first;}
}
map(const map& x)
{//_rbtree = x._rbtree;for (const auto& e : x){_rbtree.Insert(e);}
}
map& operator=(const map& x)
{_rbtree = x._rbtree;return *this;
}
使用红黑树封装map和set的源代码:https://gitee.com/xie-zhus-shovel/c-learning/tree/master/C%2B%2BLearning/%E4%BD%BF%E7%94%A8%E7%BA%A2%E9%BB%91%E6%A0%91%E5%B0%81%E8%A3%85set%E5%92%8Cmap
最后
本篇关于使用红黑树封装map和set的实现到这里就结束了,难度还是蛮大的,需要大家多去敲代码,其中还有很多细节值得我们去探究,需要我们不断地学习。如果本篇内容对你有帮助的话就给一波三连吧,对以上内容有异议或者需要补充的,欢迎大家来讨论!