【C++进阶】RBTree封装map与set

1.红黑树的迭代器

1.1 begin()

begin()就是红黑树的开头,那么对于红黑树来说按照中序序列是该树的最左节点。

	Iterator Begin()
	{
		Node* leftMin = _root;
		while (leftMin->_left)
		{
			leftMin = leftMin->_left;
		}
		return Iterator(leftMin);
	}

1.2 end()

begin()就是红黑树的结尾的下一个,那么对于红黑树来说按照中序序列应该是该树的最右节点的下一个位置,但下一个位置是nullptr(这里库中源码写的是使用了一个哨兵位的头节点作为End,我们可以简单来写,以nullptr作为End)。

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

1.3 operator++

Self& operator++()
{
	//1.右不为空,下一个是右子树最左节点
	if (_node->_right)
	{
		Node* leftMin = _node->_right;
		while (leftMin->_left)
		{
			leftMin = leftMin->_left;
		}
		_node = leftMin;
	}
	//2.右为空,下一个倒着在祖先中找孩子是父亲的左的祖先节点
	else
	{
		Node* cur = _node;
		Node* parent = cur->_parent;
		while (parent && cur == parent->_right)
		{
			cur = parent;
			parent = cur->_parent;
		}
		_node = parent;
	}
	return *this;
}

2.改造红黑树

因为我们之前写的红黑树是不能同时满足set和map的使用,如果需要还必须再写一份来满足另一个,那么我们可不可以把红黑树改造成能同时满足set和map呢?

答案是可以的,我们实质上是偷了个懒,把写另一个的事情交给编译器去做,这也是能体现面向对象中封装的特性的!

#pragma once
#include<vector>

enum Color
{
	RED,
	BLACK
};
template<class T>
struct RBTreeNode
{
	RBTreeNode<T>* _left;	//该节点的左孩子
	RBTreeNode<T>* _right;	//该节点的右孩子
	RBTreeNode<T>* _parent;	//该节点的双亲

	Color _col;
	T _data;	//存放Key或者pair

	RBTreeNode(const T& data)	//该节点初始化
		:_left(nullptr)
		, _right(nullptr)
		, _parent(nullptr)
		, _data(data)
		, _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)
	{}
	Ref operator*() 
	{
		return _node->_data;
	}
	Ptr operator->()
	{
		return &_node->_data;
	}
	bool operator!=(const Self& s)
	{
		return _node != s._node;
	}
	Self& operator++()
	{
		//1.右不为空,下一个是右子树最左节点
		if (_node->_right)
		{
			Node* leftMin = _node->_right;
			while (leftMin->_left)
			{
				leftMin = leftMin->_left;
			}
			_node = leftMin;
		}
		//2.右为空,下一个倒着在祖先中找孩子是父亲的左的祖先节点
		else
		{
			Node* cur = _node;
			Node* parent = cur->_parent;
			while (parent && cur == parent->_right)
			{
				cur = parent;
				parent = cur->_parent;
			}
			_node = parent;
		}
		return *this;
	}
};

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;

	RBTree() = default;

	//t2(t1)
	RBTree(const RBTree<K, T, KeyOfT>& t)
	{
		_root = Copy(t._root);
	}
	~RBTree()
	{
		Destroy(_root);
		_root = nullptr;
	}
	//t2 = t1
	RBTree<K, T, KeyOfT>& operator=(const RBTree<K, T, KeyOfT> t)
	{
		swap(_root, t._root);
		return *this;
	}
	Iterator Begin()
	{
		Node* leftMin = _root;
		while (leftMin->_left)
		{
			leftMin = leftMin->_left;
		}
		return Iterator(leftMin);
	}
	Iterator End()
	{
		return Iterator(nullptr);
	}
	ConstIterator Begin() const
	{
		Node* leftMin = _root;
		while (leftMin->_left)
		{
			leftMin = leftMin->_left;
		}
		return ConstIterator(leftMin);
	}
	ConstIterator End() const
	{
		return ConstIterator(nullptr);
	}
	Iterator Find(const K& key)
	{
		Node* cur = _root;
		while (cur)
		{
			if (cur->_key < key)
			{
				cur = cur->_right;
			}
			else if (cur->_key > key)
			{
				cur = cur->_left;
			}
			else
			{
				return Iterator(cur);
			}
		}

		return End();
	}
	pair<Iterator, bool> Insert(const T& data)
	{
		if (_root == nullptr)
		{
			_root = new Node(data);
			_root->_col = BLACK;
			return make_pair(Iterator(_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), 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 = BLACK;
					uncle->_col = BLACK;
					grandfather->_col = RED;

					//继续往上调整
					cur = grandfather;
					parent = cur->_parent;
				}
				else //叔叔不存在/叔叔存在且为黑 -->旋转操作
				{
					if (cur == parent->_left)
					{
						//      g
						//    p   u
						//  c
						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
			{
				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 (cur == parent->_right)
					{
						//     g
						//   u   p 
						//         c
						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 make_pair(Iterator(newnode), true);
	}
	void RotateR(Node* parent)
	{
		Node* subL = parent->_left;
		Node* subLR = subL->_right;
		parent->_left = subLR;
		if (subLR)	//subLR有可能为空,不为空时才能调整subLR的父节点
			subLR->_parent = parent;
		subL->_right = parent;
		//parent不一定就是根节点,也可能是子树,所以要设置一个ppNode来标记parent的父节点
		Node* ppNode = parent->_parent;
		parent->_parent = subL;

		if (parent == _root)
		{
			_root = subL;
			_root->_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有可能为空,不为空时才能调整subRL的父节点
			subRL->_parent = parent;
		subR->_left = parent;
		//parent不一定就是根节点,也可能是子树,所以要设置一个ppNode来标记parent的父节点
		Node* ppNode = parent->_parent;
		parent->_parent = subR;

		if (parent == _root)
		{
			_root = subR;
			_root->_parent = nullptr;
		}
		else
		{
			if (ppNode->_left == parent)
			{
				ppNode->_left = subR;
			}
			else
			{
				ppNode->_right = subR;
			}
			subR->_parent = ppNode;
		}
	}
	void InOrder()
	{
		_InOrder(_root);
		cout << endl;
	}
	bool IsBalance()
	{
		//检查规则1
		if (_root->_col == RED)
		{
			return false;
		}
		int refNum = 0;
		Node* cur = _root;
		while (cur)
		{
			if (cur->_col == BLACK)
				++refNum;
			cur = cur->_left;
		}
		return Check(_root, 0, refNum);
	}
private:
	Node* Copy(Node* root)
	{
		if (root == nullptr)
			return nullptr;
		Node* newroot = new Node(root->_data);
		newroot->_col = root->_col;

		newroot->_left = Copy(root->_left);
		if (newroot->_left)
			newroot->_left->_parent = newroot;
		newroot->_right = Copy(root->_right);
		if (newroot->_right)
			newroot->_right->_parent = newroot;
		return newroot;
	}
	void Destroy(Node* root)
	{
		if (root == nullptr)
			return;
		Destroy(root->_left);
		Destroy(root->_right);
		delete root;
		root = nullptr;
	}
	bool Check(Node* root, int blackNum, const int refNum)
	{
		if (root == nullptr)
		{
			//检查规则4
			if (blackNum != refNum)
			{
				cout << "存在黑色节点不相等的路径" << endl;
				return false;
			}
			return true;
		}

		//检查规则3
		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);
	}
	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;
	//size_t size = 0;	//可以用来记录节点个数
};

3.set的模拟实现

set的底层为红黑树,因此只需在set内部封装一棵红黑树,即可将该容器实现出来。

#pragma once

namespace bit
{
	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();
		}
		iterator find(const K& key)
		{
			return _t.Find(key);
		}
		pair<iterator, bool> insert(const K& key)
		{
			return _t.Insert(key);
		}
	private:
		RBTree<K, const K, SetKeyOfT> _t;
	};
	void PrintSet(const set<int>& s)
	{
		for (auto e : s)
		{
			cout << e << endl;
		}
	}
	void test_set()
	{
		set<int> s;
		s.insert(4);
		s.insert(2);
		s.insert(5);
		set<int>::iterator it = s.begin();
		while (it != s.end())
		{
			//*it += 5;

			cout << *it << " ";
			++it;
		}
		cout << endl;

		for (auto e : s)
		{
			cout << e << endl;
		}
		PrintSet(s);
	}
}

4.map的模拟实现

map的底层结构就是红黑树,因此在map中直接封装一棵红黑树,然后将其接口包装下即可

#pragma once

namespace bit
{
	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();
		}
		iterator find(const K& key)
		{
			return _t.Find(key);
		}
		pair<iterator, bool> insert(const pair<K, V>& kv)
		{
			return _t.Insert(kv);
		}

		V& operator[](const K& key)
		{
			pair<iterator, bool> ret = _t.Insert(make_pair(key, V()));
			return ret.first->second;
		}
	private:
		RBTree<K, pair<const K, V>, MapKeyOfT> _t;
	};
	void test_map1()
	{
		map<string, int> m;
		m.insert({"苹果", 1});
		m.insert({ "香蕉", 2});
		m.insert({ "梨子",3});

		map<string, int>::iterator it = m.begin();
		while (it != m.end())
		{
			//it->first += 'x';
			it->second += 1;

			//cout << it.operator->()->first << ":" << it->second << endl;
			cout << it->first << ":" << it->second << endl;
			++it;
		}
		cout << endl;
	}

	void test_map2()
	{
		string arr[] = { "草莓", "香蕉", "梨子", "苹果", "梨子", "苹果", "香蕉",
"草莓", "苹果", "苹果", "梨子","梨子","草莓", "苹果","苹果" };
		map<string, int> countMap;
		for (auto& e : arr)
		{
			countMap[e]++;
		}

		for (auto& kv : countMap)
		{
			cout << kv.first << ":" << kv.second << endl;
		}
		cout << endl;
	}
}

5.test.cpp

#include<iostream>
using namespace std;

#include"RBTree.h"
#include"Myset.h"
#include"Mymap.h"

int main()
{
	bit::test_map1();
	bit::test_set();
	bit::test_map2();
	return 0;
}

 依次展开头文件就可正常使用set与map了。

上一篇:Nginx服务配置


下一篇:Spring Cloud Netflix 之 Eureka-前言