c++逆天改命进阶--map_set的模拟实现

1.RedBlackTree.h

#pragma once
#include <iostream>
#include "Iterator.h"
using namespace std;

enum Color
{
	BLACK,
	RED
};
template<class T>
struct RBTreeNode
{
	RBTreeNode<T>* _left;
	RBTreeNode<T>* _right;
	RBTreeNode<T>* _parent;
	T _data;
	Color _col;
	RBTreeNode(const T& x)
		:_left(nullptr)
		,_right(nullptr)
		,_parent(nullptr)
		,_data(x)
		,_col(RED)
	{}
};


template <class T, class Ref, class Ptr>
struct _TreeIterator
{
	typedef Ref reference;
	typedef Ptr pointer;
	typedef RBTreeNode<T> Node;
	typedef _TreeIterator<T, Ref, Ptr> Self;
	Node* _pNode;
	_TreeIterator(Node* pNode)
		:_pNode(pNode)
	{}

	Ref operator* ()
	{
		return _pNode->_data;
	}
	Ptr operator->()
	{
		return &_pNode->_data;
	}

	bool operator !=(const Self& s)const
	{
		return _pNode != s._pNode;
	}
	bool operator ==(const Self& s)const
	{
		return _pNode == s._pNode;
	}
	Self& operator++()
	{
		if (_pNode->_right)
		{
			Node* left = _pNode->_right;
			while (left->_left)
			{
				left = left->_left;
			}
			_pNode = left;
		}
		else
		{
			Node* cur = _pNode;
			Node* parent = cur->_parent;
			while (parent && cur == parent->_right)
			{
				cur = parent;
				parent = cur->_parent;
			}
			_pNode = parent;
		}
		return *this;
	}
	Self& operator--()
	{
		if (_pNode->_left)
		{
			Node* right = _pNode->_left;
			while (right->_right)
			{
				right = right->_right;
			}
			_pNode = right;
		}
		else
		{
			Node* cur = _pNode;
			Node* parent = cur->_parent;
			while (parent && cur == parent->_left)
			{
				cur = parent;
				parent = cur->_parent;
			}
			_pNode = parent;
		}
		return *this;
	}

};
template<class K,class T, class KeyofT>
class RBTree
{
	typedef RBTreeNode<T> Node;
public:
	typedef _TreeIterator<T, T&, T*> iterator;
	typedef ReverseIterator<iterator> reverse_iterator;

	reverse_iterator rbegin()
	{
		Node* right = _root;
		while (right && right->_right)
		{
			right = right->_right;
		}
		return reverse_iterator(iterator(right));

	}
	reverse_iterator rend()
	{		
		return reverse_iterator(iterator(nullptr));
	}

	iterator begin()
	{
		Node* left = _root;
		while (left && left->_left)
		{
			left = left->_left;
		}
		return iterator(left);
	}
	iterator end()
	{
		return iterator(nullptr);
	}
	RBTree()
		:_root(nullptr)
	{}
	void _Destory(Node* root)
	{
		if (root == nullptr)
		{
			return;
		}
		_Destory(root->_left);
		_Destory(root->_right);
		delete root;
	}
	~RBTree()
	{
		_Destory(_root);
		_root = nullptr;
	}
	Node* Find(const K& key)
	{
		KeyofT kot;
		Node* cur = _root;
		while (cur)
		{
			if (kot(cur->_data) > key)
			{
				cur = cur->_left;
			}
			else if (kot(cur->_data) < key)
			{
				cur = cur->_right;
			}
			else
			{
				return cur;
			}
		}
		return nullptr;
	}
	pair<Node*, bool> Insert(const T& data)
	{
		if (_root == nullptr)
		{
			_root = new Node(data);
			_root->_col = BLACK;
			return make_pair(_root, true);
        }
		KeyofT kot;
		Node* cur = _root;
		Node* parent = nullptr;
		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(cur, false);
			}
		}
		Node* newNode = new Node(data);
		newNode->_col = RED;
		//为什么我们要将新插入的节点的颜色设置为红色
		//如果我们设置为黑色,则该路径黑色节点数量相比于其他路径的黑色节点数量多了一个
		//总不可能插入一个节点就对所有路径进行更改
		//如果我们插入红色,有可能会出现连续红色节点,我们针对连续红色节点进行下面的处理

		if (kot(data) > kot(parent->_data))
		{
			parent->_right = newNode;
			newNode->_parent = parent;
		}
		else
		{
			parent->_left = newNode;
			newNode->_parent = parent;
		}
		cur = newNode;
		//当我们插入了新节点之后,可能我们破坏了红黑树的性质
		//如果父亲是黑色不用处理,如果是红色需要处理(出现了连续的红色节点)

		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);
						grandfather->_col = RED;
						parent->_col = BLACK;
					}
					else
					{
						RotateL(parent);
						RotateR(grandfather);
						grandfather->_col = RED;
						cur->_col = BLACK;
					}
					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->_left)
					{
						RotateR(parent);
						RotateL(grandfather);
						cur->_col = BLACK;
						grandfather->_col = RED;
					}
					else
					{
						RotateL(grandfather);
						parent->_col = BLACK;
						grandfather->_col = RED;
					}
					break;
				}
			}
		}
		_root->_col = BLACK;
		return make_pair(newNode, true);

	}
	void RotateL(Node* parent)//左单旋
	{
		Node* subR = parent->_right;
		Node* subRL = subR->_left;
		Node* parentParent = parent->_parent;
		parent->_right = subRL;
		if (subRL)//subRL为空就不用给subRL找父母了
		{
			subRL->_parent = parent;
		}
		parent->_parent = subR;
		subR->_left = parent;
		if (parent == _root)//如果parent是根节点,把根节点改为subR,_root的父母置为nullptr
		{
			_root = subR;
			_root->_parent = nullptr;
		}
		else//parent不是根节点
		{
			//判断parent是parentParent的左还是右
			if (parentParent->_left == parent)
			{
				parentParent->_left = subR;
			}
			else
			{
				parentParent->_right = subR;
			}
			subR->_parent = parentParent;
		}
	}

	void RotateR(Node* parent)
	{
		Node* subL = parent->_left;
		Node* subLR = subL->_right;
		Node* parentParent = parent->_parent;
		parent->_left = subLR;
		if (subLR)
		{
			subLR->_parent = parent;
		}
		parent->_parent = subL;
		subL->_right = parent;
		if (parent == _root)
		{
			_root = subL;
			_root->_parent = nullptr;
		}
		else
		{
			if (parent == parentParent->_left)
			{
				parentParent->_left = subL;
			}
			else
			{
				parentParent->_right = subL;
			}
			subL->_parent = parentParent;
		}
	}
	bool _CheckBalance(Node* root, int blackNum, int count)
	{
		if (root == nullptr)//走到空了说明要开始比较黑色节点数量
		{
			if (count != blackNum)
			{
				cout << "黑色节点数量不相等" << endl;
				return false;
			}
			return true;
		}
		if (root->_col == RED && root->_parent->_col == RED)
		{
			cout << "存在连续的红色节点" << endl;
			return false;
		}
		if (root->_col == BLACK)
			count++;
		return _CheckBalance(root->_left, blackNum, count)
			&& _CheckBalance(root->_right, blackNum, count);
	}
	bool CheckBalance()
	{
		if (_root == nullptr)//空树认为平衡
			return true;
		if (_root->_col == RED)//根节点颜色为红则不平衡
			return false;

		//通过每条路径的黑色节点数量是否全部相等来判断,且不能有连续的红色节点

		//我们先记录最左路径黑色节点的数量作为参考值
		//在依次遍历其他路径,每遍历一条路径,就将其黑色节点数量与参考值比较
		//如果遇到不相等的就不平衡

		int blackNum = 0;
		Node* cur = _root;
		while (cur)
		{
			if (cur->_col == BLACK)
				blackNum++;
			cur = cur->_left;
		}
		int count = 0;
		return _CheckBalance(_root, blackNum, count);
	
	}
	void _InOrder(Node* root)
	{
		if (root == nullptr)
			return;
		_InOrder(root->_left);
		cout << root->_kv.first << ":" << root->_kv.second << " ";
		_InOrder(root->_right);
	}
	void InOrder()
	{
		_InOrder(_root);
		cout << endl;
	}

private:
	Node* _root;
};

2.set.h

#pragma once
#include "RedBlackTree.h"

namespace ls
{
	template <class K>
	class set
	{
		struct SetKeyofT
		{
			const K& operator()(const K& key)
			{
				return key;
			}
		};
	public:
		typedef typename RBTree<K, K, SetKeyofT>::iterator iterator;
		typedef typename RBTree<K, K, SetKeyofT>::reverse_iterator reverse_iterator;

		reverse_iterator rbegin()
		{
			return _t.rbegin();
		}
		reverse_iterator rend()
		{
			return _t.rend();
		}
		iterator begin()
		{
			return _t.begin();
		}
		iterator end()
		{
			return _t.end();
		}
		pair<iterator,bool> insert(const K& key)
		{
			return _t.Insert(key);
		}
	private:
		RBTree<K, K, SetKeyofT> _t;
	};
}

3.map.h

#pragma once
#include "RedBlackTree.h"

namespace ls
{
	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<K, V>, MapKeyofT>::iterator iterator;
		typedef typename RBTree<K, pair<K, V>, MapKeyofT>::reverse_iterator reverse_iterator;
		reverse_iterator rbegin()
		{
			return _t.rbegin();
		}
		reverse_iterator rend()
		{
			return _t.rend();
		}

		iterator begin()
		{
			return _t.begin();
		}
		iterator end()
		{
			return _t.end();
		}

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

4.Iterator.h

#pragma once

//反向迭代器
template <class Iterator>
struct ReverseIterator
{
	typedef typename Iterator::reference Ref;
	typedef typename Iterator::pointer Ptr;
	typedef ReverseIterator<Iterator> Self;
	Iterator _it;
	ReverseIterator(Iterator it)
		:_it(it)
	{}

	Ref operator*()
	{
		return *_it;
	}

	Ptr operator->()
	{
		return _it.operator->();
	}
	Self& operator++()
	{
		--_it;
		return *this;
	}
	Self& operator--()
	{
		++_it;
		return *this;
	}

	bool operator!=(const Self& s)const
	{
		return _it != s._it;
	}
	bool operator==(const Self& s)const
	{
		return _it == s._it;
	}

};

5.test.cpp

#include "RedBlackTree.h"
#include "map.h"
#include "set.h"

int main()
{
	ls::map<int, int> m;
	m.insert(make_pair(1, 1));
	m.insert(make_pair(3, 3));
	m.insert(make_pair(0, 0));
	m.insert(make_pair(9, 9));
	m.insert(make_pair(12, 12));

	ls::map<int, int>::iterator it = m.begin();
	while (it != m.end())
	{
		//cout << (*it).first << ":" << (*it).second << endl;
		cout << it->first << ":" << it->second << endl;
		++it;
	}


	ls::set<int> s;
	s.insert(1);
	s.insert(5);
	s.insert(2);
	s.insert(1);
	s.insert(13);
	s.insert(0);
	s.insert(15);
	s.insert(18);

	ls::set<int>::iterator sit = s.begin();
	while (sit != s.end())
	{
		cout << *sit << " ";
		++sit;
	}
	cout << endl;

	ls::set<int>::reverse_iterator rsit = s.rbegin();
	while (rsit != s.rend())
	{
		cout << *rsit << " ";
		++rsit;
	}
	cout << endl;

	ls::map<string, string> dict;
	dict["happy"];
	dict["left"] = "左边";
	dict["left"] = "剩余";
	for (auto e : dict)
	{
		cout << e.first << ":" << e.second << endl;

	}
	dict["happy"] = "开心的";
	for (auto e : dict)
	{
		cout << e.first << ":" << e.second << endl;

	}
	return 0;
}

6.迭代器operator++/–

image-20220605182946613

image-20220605183028204

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

逃跑的机械工

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值