在这里插入图片描述

🫧 励志不掉头发的内向程序员个人主页

 ✨️ 个人专栏: 《C++语言》《Linux学习》

🌅偶尔悲伤,偶尔被幸福所完善


👓️博主简介:

在这里插入图片描述


前言

前面我们已经学习了两种优化二叉搜索树的方法,此时我们便可以尝试着用其中一种方法去封装我们的 map/set,我们这里要选取的办法是用红黑树去封装,因为它与 AVL 树相比旋转次数会大大减少,所以如果不知道红黑树的还请到上一章去学习一下再来。

在这里插入图片描述


一、源码及框架分析

我们在了解了红黑树的原理和 map/set 的功能,大家可能会觉得实现起来没有什么难度,就是和之前一样,之前的容器甚至都不知道其底层原理,但是现在我们的 map/set 知道了,那不是直接套用即可啦,这么想是没错,但是那些作为开发 STL 库的顶尖大佬,并不想这么实现,他们认为这样太挫了,我们先来看看他们的思路。

在这里插入图片描述
在这里我们可以看到,大佬对红黑树去封装我们的 map/set 主要运用的是一个泛型思想,非常的巧妙。

  • 在源码中 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。
  • rb_tree 第二个模板参数 Value 已经控制了红黑树结点中存储的数据类型,为什么还要传第一个模板参数 Key 呢,尤其是 set,它两个模板参数是一样的?要注意的是对于 map 和 set,find/erase 时的函数参数都是 Key,所以第一个模板参数是传给 find/erase 等函数做形参的类型的。对于 set 而言两个参数都是一样的,但是对于 map 而言就完全不一样了,map 的 insert 的形参是 pair 对象,但是 find/erase 的形参是 Key 对象。

注意:

源码里面模板参数是用 T 代表 value,而内部写的 value_type 不是我们日常 key/value 场景中说的 value,源码中的 value_type反而是红黑树结点中存储的真实的数据的类型。


二、利用红黑树实现框架,并支持 insert

通过上面我们就可以发现,人和人的区别是真的大,如果让我们去实现,大概就是用两个不同的红黑树去分别实现 map/set 了,我们参考源码的框架,来让 map/set 复用红黑树。我们在这里调整了一下参数的名字, key 的参数为 K,value 的参数为 V,红黑树中的数据类型,我们使用 T,因为源码的命名有点混乱啦

红黑树(上一章节实现过了):

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;
	}
};

我们可以看到,我们想要红黑树存储什么样的类型,主要就是看我们传给红黑树的 T 是什么类型的,然后 T 去创建我们所需要的结点,存储在我们的红黑树中。
此时我们只需要让我们的 set 类传给红黑树的 T 为 key,而 map 则传输给红黑树的类型为 pair 即可。

// Mymap.h
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
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;
};

此时我们就可以看到,我们 map 和 set 传给红黑树的 T 的类型是不同的。
在这里插入图片描述
有细心的人可能发现了我们在实现 map 类和 set 类时还随便实现了仿函数,这是因为红黑树实现了泛型所以不知道 T 参数会是 K 还是 pair<K, V>,那么 insert 内部进行插入逻辑比较时,就没有办法进行比较,因为 pair 的默认支持的是 key 和 value 一起参与比较,我们需要时的任何时候只比较 key,所以我们在 map 和 set 层分别实现⼀个 MapKeyOfT 和 SetKeyOfT 的仿函数传给红黑树的 KeyOfT,然后红黑树中通过 KeyOfT 仿函数取出 T 类型对象中的 key,再进行比较。

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); 
}

三、iterator 的实现

我们在实现了基本框架后,我们这个时候也可以来看看怎么实现迭代器的,我们的 map/set 和 list 一样在物理空间都是不连续的,也就是说我们想要实现 map/set 的迭代器就得自己去实现一个迭代器的类型,在里面有能够找到下一个迭代器的赋值重载,这也是我们实现它的难点,我们就来一起看看吧。

iterator 实现的大框架:
跟 list 的 iterator 思路是一致的,用一个类型封装结点的指针,再通过重载运算符实现迭代器像指针一样的访问行为。

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++()
	{}
	Self& operator--()
	{}
	Ref operator*()
	{}
	Ptr operator->()
	{}
	bool operator!= (const Self& s) const
	{}
	bool operator== (const Self& s) const
	{}
};

iterator实现思路分析:

  • 这里的难点是 operator++ 和 operator-- 的实现。之前使用部分,我们分析了,map 和 set 的迭代器走的是中序遍历,左子树 -> 根结点 -> 右子树,那么 begin() 会返回中序第⼀个结点的 iterator。

在这里插入图片描述

typedef RBTreeIterator<T, T&, T*> Iterator;
typedef RBTreeIterator<T, const T&, const T*> ConstIterator;
Iterator Begin()
{
	Node* leftMost = _root;
	while (leftMost && leftMost->_left)
	{
		leftMost = leftMost->_left;
	}
	return Iterator(leftMost, _root);
}

ConstIterator Begin() const
{
	Node* leftMost = _root;
	while (leftMost && leftMost->_left)
	{
		leftMost = leftMost->_left;
	}
	return ConstIterator(leftMost, _root);
}
  • 迭代器 ++ 的核心逻辑就是不看全局,只看局部,只考虑当前中序局部要访问的下⼀个结点。
  • 迭代器 ++ 时,如果 it 指向的结点的右子树不为空,代表当前结点已经访问完了,要访问下⼀个结点是右子树的中序第一个,一棵树中序第⼀个是最左结点,所以直接找右子树的最左结点即可。

在这里插入图片描述

// 右不为空,右⼦树最左结点就是中序第⼀个
Node* leftMost = _node->_right;
while (leftMost->_left)
{
	leftMost = leftMost->_left;
}
_node = leftMost;
  • 迭代器 ++ 时,如果 it 指向的结点的右子树空,代表当前结点已经访问完了且当前结点所在的子树也访问完了,要访问的下⼀个结点在当前结点的祖先里面,所以要沿着当前结点到根的祖先路径向上找。
  • 如果当前结点是父亲的左,根据中序左子树 -> 根结点 -> 右子树,那么下一个访问的结点就是当前结点的父亲。
  • 如果当前结点是父亲的右,根据中序左子树 -> 根结点 -> 右子树,当前结点所在的子树访问完了,当前结点所在父亲的子树也访问完了,那么下⼀个访问的需要继续往根的祖先中去找,直到找到孩子是父亲左的那个祖先就是中序要找的下⼀个结点。

在这里插入图片描述
在这里插入图片描述

// 孩⼦是⽗亲左的那个祖先
Node* cur = _node;
Node* parent = cur->_parent;
while (parent && cur == parent->_right)
{
	cur = parent;
	parent = cur->_parent;
}
_node = parent;

注意:

之所以是找到孩子是父亲的左边,那是因为如果孩子是在父亲右边,此时 parent -> right = cur,那我们的 cur 是比 parent 大的,也就是说我们肯定已经选取过 parent 了(因为 cur 比 parent 大),所以我们应该找比 cur 大的。

  • 迭代器 – 的实现跟 ++ 的思路完全类似,逻辑正好反过来即可,因为他访问顺序是右子树 -> 根结点 -> 左子树。
if (_node == nullptr) // end()
{
	// --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 = cur->_parent;
	}
	_node = parent;
}
return *this;
  • end() 如何表示呢?如下图:当 it 指向 50 时,++it 时,50 是 40 的右,40 是 30 的右,30 是 18 的右,18 到根没有父亲,没有找到孩子是父亲左的那个祖先,这是父亲为空了,那我们就把 it 中的结点指针置为 nullptr,我们用 nullptr 去充当 end。

在这里插入图片描述

注意:

STL 源码中,红黑树增加了⼀个哨兵位头结点做为 end(),这哨兵位头结点和根互为父亲,左指向最左结点,右指向最右结点。相比我们用 nullptr 作为 end(),差别不大,他能实现的,我们也能实现。只是 --end() 判断到结点时特殊处理⼀下,让迭代器结点指向最右结点。具体参考迭代器 – 实现。

Iterator End()
{
	return Iterator(nullptr, _root);
}

ConstIterator End() const
{
	return ConstIterator(nullptr, _root);
}
  • 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;
// mymap.h
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 _t.Begin();
}
iterator end()
{
	return _t.End();
}
const_iterator begin() const
{
	return _t.Begin();
}
const_iterator end() const
{
	return _t.End();
}

// myset.h
typedef typename RBTree<K, const K, SetKeyOfT>::Iterator iterator;
typedef typename RBTree<K, const K, SetKeyOfT>::ConstIterator const_iterator;

iterator begin()
{
	return _t.Begin();
}
iterator end()
{
	return _t.End();
}
const_iterator begin() const
{
	return _t.Begin();
}
const_iterator end() const
{
	return _t.End();
}

迭代器运行原理图:

在这里插入图片描述
实现完 ++ 和 --,剩下的部分非常简单。

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; }

和 list 基本上没有什么区别。


四、map 支持 [ ]

我们 map 的 [ ] 在实现了 insert 的基础上想要支持此操作就变得非常的简单啦,只需要先把我们的 insert 的返回值改一下,然后直接复用我们的 insert 函数即可轻松实现。

map 要支持 [ ] 主要需要修改 insert 返回值支持,修改红黑树中的 insert 返回值为 pair<Iterator, bool> Insert(const T& data)。

V& operator[](const K& key)
{
pair<iterator, bool> ret = insert(make_pair(key, V()));
return ret.first->second;
}

五、mymap 和 myset 代码实现

我们还有一些成员函数都是非常简单的,我们可以直接接写,也没有什么必要去讲啦,还有就是这里也不讲怎么删除我们的结点,等到后面有机会了在说。

// 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)
	{
	}
};
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* leftMost = _node->_right;
			while (leftMost->_left)
			{
				leftMost = leftMost->_left;
			}
			_node = leftMost;
		}
		else
		{
			// 孩⼦是⽗亲左的那个祖先
			Node* cur = _node;
			Node* parent = cur->_parent;
			while (parent && cur == parent->_right)
			{
				cur = parent;
				parent = cur->_parent;
			}
			_node = parent;
		}
		return *this;
	}
	Self& operator--()
	{
		if (_node == nullptr) // end()
		{
			// --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 = 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* leftMost = _root;
		while (leftMost && leftMost->_left)
		{
			leftMost = leftMost->_left;
		}
		return Iterator(leftMost, _root);
	}
	Iterator End()
	{
		return Iterator(nullptr, _root);
	}
	ConstIterator Begin() const
	{
		Node* leftMost = _root;
		while (leftMost && leftMost->_left)
		{
			leftMost = leftMost->_left;
		}
		return ConstIterator(leftMost, _root);
	}
	ConstIterator End() const
	{
		return ConstIterator(nullptr, _root);
	}
	RBTree() = default;
	~RBTree()
	{
		Destroy(_root);
		_root = nullptr;
	}
	pair<Iterator, bool> Insert(const T & data)
	{
		if (_root == nullptr)
		{
			_root = new Node(data);
			_root->_col = BLACK;
			return make_pair(Iterator(_root, _root), 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 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)
			{
				Node* uncle = grandfather->_right;
				if (uncle && uncle->_col == RED)
				{
					parent->_col = uncle->_col = BLACK;
					grandfather->_col = RED;
					cur = grandfather;
					parent = cur->_parent;
				}
				else
				{
					if (cur == parent->_left)
					{
						RotateR(grandfather);
						parent->_col = BLACK;
						grandfather->_col = RED;
					}
					else
					{
						RotateL(parent);
						RotateR(grandfather);
						cur->_col = BLACK;
						grandfather->_col = RED;
					}
					break;
				}
			}
			else
			{
				Node* uncle = grandfather->_left;
				if (uncle && uncle->_col == RED)
				{
					parent->_col = uncle->_col = BLACK;
					grandfather->_col = RED;
					cur = grandfather;
					parent = cur->_parent;
				}
				else 
				{
					if (cur == parent->_right)
					{
						RotateL(grandfather);
						parent->_col = BLACK;
						grandfather->_col = RED;
					}
					else
					{
						RotateR(parent);
						RotateL(grandfather);
						cur->_col = BLACK;
						grandfather->_col = RED;
					}
					break;
				}
			}
		}
		_root->_col = BLACK;
		return make_pair(Iterator(newnode, _root), true);
}
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();
}
private:
	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 RotateR(Node* parent)
	{
		Node* subL = parent->_left;
		Node* subLR = subL->_right;
		parent->_left = subLR;
		if (subLR)
			subLR->_parent = parent;
		Node* parentParent = parent->_parent;
		subL->_right = parent;
		parent->_parent = subL;
		if (parentParent == nullptr)
		{
			_root = subL;
			subL->_parent = nullptr;
		}
		else
		{
			if (parent == parentParent->_left)
			{
				parentParent->_left = subL;
			}
			else
			{
				parentParent->_right = subL;
			}
			subL->_parent = parentParent;
		}
	}
	void Destroy(Node* root)
	{
		if (root == nullptr)
			return;
		Destroy(root->_left);
		Destroy(root->_right);
		delete root;
	}
private:
	Node* _root = nullptr;
};
// Myset.h
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 _t.Begin(); }
	iterator end()
	{ return _t.End(); }
	const_iterator begin() const
	{ return _t.Begin(); }
	const_iterator end() const
	{ return _t.End(); }
	pair<iterator, bool> insert(const K& key)
	{ return _t.Insert(key); }
	iterator find(const K& key)
	{ return _t.Find(key); }
private:
	RBTree<K, const K, SetKeyOfT> _t;
};
// Mymap.h
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 _t.Begin(); }
	iterator end()
	{ return _t.End(); }
	const_iterator begin() const
	{ return _t.Begin(); }
	const_iterator end() const
	{ return _t.End(); }
	pair<iterator, bool> insert(const pair<K, V>& kv)
	{ return _t.Insert(kv); }
	iterator find(const K& key)
	{ return _t.Find(key); }
	V& operator[](const K& key)
	{
		pair<iterator, bool> ret = insert(make_pair(key, V()));
		return ret.first->second;
	}
private:
	RBTree<K, pair<const K, V>, MapKeyOfT> _t;
};


总结

以上便是我们 map 和 set 实现的主要流程,这里面的难点主要在于迭代器中 ++ 和 – 的逻辑以及我们泛型思想可能比较难想到,我们可以多多看看代码,自己去屡屡思路,多画画图,其实把它绕明白了也就非常简单了。

在这里插入图片描述

🎇坚持到这里已经很厉害啦,辛苦啦🎇
ʕ • ᴥ • ʔ
づ♡ど
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐