【C++进阶】红黑树模拟实现mymap和myset

🎬 博主名称键盘敲碎了雾霭
🔥 个人专栏 : 《C语言》《数据结构》 《C++》 《Matlab》 《Python》

⛺️指尖敲代码,雾霭皆可破


文章目录

一、底层框架分析

  • 通过对框架的分析,我们可以看到源码中rb_tree用了一个巧妙的泛型思想实现,rb_tree是实现key的搜索场景,还是key/value的搜索场景不是直接写死的,而是由第二个模板参数Value决定_rb_tree_node中存储的数据类型。
  • set实例化rb_tree时第二个模板参数给的是key,map实例化rb_tree时第二个模板参数给的是pair<constkey,T>,这样一颗红黑树既可以实现key搜索场景的set,也可以实现key/value搜索场景的map。
  • 源码中的value_type反而是红黑树结点中存储的真实的数据的类型。
  • 要注意的是对于map和set,find/erase时的函数参数都是Key,所以第一个模板参数是传给find/erase等函数做形参的类型的。对于set而言两个参数是一样的,但是对于map而言就完全不一样了,mapinsert的是pair对象,但是find和ease的是Key对象

二、模拟实现map和set

实现步骤如下:

1、实现红黑树

2、封装map和set框架,解决KeyOfT

3、iterator

4、const_iterato

5、key不支持修改的问题

6、operator\[\]

2.1 复用红黑树

对红黑树不了解的小伙伴看这篇回顾

【C++进阶】手撕红黑树:从原理到实现,万字详解插入、旋转与变色
https://blog.csdn.net/2401_89538720/article/details/161484023?fromshare=blogdetail&sharetype=blogdetail&sharerId=161484023&sharerefer=PC&sharesource=2401_89538720&sharefrom=from_link

2.2 insert的实现

  • 为RBTree实现了泛型不知道T参数导致是K,还是pair<K,V>,那么insert内部进行插入逻辑比较时,就没办法进比较,因为pair的默认支持的是key和value一起参与比较,我们需要时的任何时候只比较key,所以我们在map和set层分别实现一个MapKeyOfT和SetKeyOfT的仿函数传给RBTree的KeyOfT,然后RBTree中通过KeyOfT仿函数取出T类型对象中的key,再进行比较,具体细节参考如下代码实现
  • insert的返回值方便实现[]
cpp 复制代码
pair<Iterator,bool> Insert(const T& data)
{
	KeyofT Kot;
	if (_root == nullptr)
	{
		_root = new Node(data);
		_root->_parent = nullptr;
		_root->_col = Black;
		return { Iterator(_root,_root) ,true};
	}
	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 { Iterator(cur,_root) ,false };
		}
	}
	cur = new Node(data);
	Node* newnode = cur;
	cur->_col = Red;
	if (Kot(parent->_data) > Kot(data))
	{
		parent->_left = cur;
	}
	else
	{
		parent->_right = cur;
	}
	cur->_parent = parent;
	while (parent&&parent->_col==Red)
	{
		Node* grandfather = parent->_parent;
		if (grandfather->_left == parent)
		{
			Node* uncle = grandfather->_right;
			if (uncle&&uncle->_col == Red)
			{
				grandfather->_col = Red;
				parent->_col = Black;
				uncle->_col = Black;
				cur = grandfather;
				parent = grandfather->_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)
			{
				grandfather->_col = Red;
				parent->_col = Black;
				uncle->_col = Black;
				cur = grandfather;
				parent = grandfather->_parent;
			}
			else
			{
				if (parent->_right==cur)
				{
					RotateL(grandfather);
					grandfather->_col = Red;
					parent->_col = Black;
				}
				else
				{
					RotateR(parent);
					RotateL(grandfather);
					grandfather->_col = Red;
					cur->_col = Black;
				}
				break;
			}
		}
	}
	_root->_col = Black;
	return { Iterator(newnode,_root) ,true };
}

2.3 iterator实现

  • **iterator实现的大框架跟list的iterator思路是一致的,用一个类型封装结点的指针,再通过重载运算符实现,迭代器像指针一样访问的行为。
  • 迭代器++的核心逻辑就是不看全局,只看局部 ,只考虑当前中序局部要访问的下一个结点。迭代器++时,如果it指向的结点的右子树不为空 ,代表当前结点已经访问完了,要访问下一个结点是右子树的中序第一个,一棵树中序第一个是最左结点,所以直接找右子树的最左结点 即可,如果it指向的结点的右子树为空 ,代表当前结点已经访问完了且当前结点所在的子树也访问完了,要访问的下个结点在当前结点的祖先面,所以要沿着当前结点到根的祖先路径向上找,当节点为祖先的左边,则找到祖先(孩子是父亲左的那个祖先
  • 迭代器--的实现跟++的思路完全类似,逻辑正好反过来即可,因为他访问顺序是右子树->根结点->左子树,具体参考下面代码实现。
cpp 复制代码
	Self operator++()
	{
		if (_node->_right)
		{
			Node* cur = _node->_right;
			while (cur->_left)
			{
				cur = cur->_left;
			}
			_node = cur;
		}
		else
		{
			Node* cur = _node;
			Node* parent = cur->_parent;
			while (parent&&parent->_right == cur)
			{
				cur = parent;
				parent = cur->_parent;
			}
			_node = parent;
		}
		return *this;
	} 
	Self operator--()
	{
		if (_node == nullptr)
		{
			Node* cur = _root;
			while (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 = cur->_parent;
			while (parent&&parent->_left == cur)
			{
				cur = parent;
				parent = cur->_parent;
			}
			_node = parent;
		}
		return *this;
	}
  • 当没有找到孩子是父亲左的那个祖先,这是父亲为空了,那我们就把it中的结点指针置为nullptr,我们nullptr去充当end(),当end()判断到结点时空,特殊处理一下,让迭代器结点指向最右结点
  • iterator也不支持修改,我们把setmap的第二个模板参数改成const Kpair<const K,V>即可
    代码实现
cpp 复制代码
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* cur = _node->_right;
			while (cur->_left)
			{
				cur = cur->_left;
			}
			_node = cur;
		}
		else
		{
			Node* cur = _node;
			Node* parent = cur->_parent;
			while (parent&&parent->_right == cur)
			{
				cur = parent;
				parent = cur->_parent;
			}
			_node = parent;
		}
		return *this;
	} 
	Self operator--()
	{
		if (_node == nullptr)
		{
			Node* cur = _root;
			while (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 = cur->_parent;
			while (parent&&parent->_left == cur)
			{
				cur = parent;
				parent = cur->_parent;
			}
			_node = parent;
		}
		return *this;
	}
	Ref operator*()
	{
		return _node->_data;
	}
	Ptr operator->()
	{
		return &_node->_data;
	}
	bool operator==(const Self& s )
	{
		return _node == s._node;
	}
	bool operator!=(const Self& s )
	{
		return _node != s._node;
	}
};

2.4 \[\]的实现

map要支持[主要需要修改insert返回值支持,修改RBtree中的insert返回值为pair<iterator,bool>

这样既可以充当修改又可以充当查改

代码实现

cpp 复制代码
		V& operator[](const K& Key)
		{
			pair<iterator,bool> tmp=_t.Insert({Key,V()});
			return tmp.first->second;
		}

三、完整代码

3.1 RBTree.h

cpp 复制代码
#pragma once
#include<iostream>
using namespace std;
enum Color
{
	Red,
	Black
};

template<class T>
struct RBTreeNode
{
	RBTreeNode<T>* _left;
	RBTreeNode<T>* _right;
	RBTreeNode<T>* _parent;
	Color _col;
	T _data;
	RBTreeNode(const T& data)
		:_left(nullptr)
		, _right(nullptr)
		, _parent(nullptr)
		,_data(data)
	{

	}

};

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* cur = _node->_right;
			while (cur->_left)
			{
				cur = cur->_left;
			}
			_node = cur;
		}
		else
		{
			Node* cur = _node;
			Node* parent = cur->_parent;
			while (parent&&parent->_right == cur)
			{
				cur = parent;
				parent = cur->_parent;
			}
			_node = parent;
		}
		return *this;
	} 
	Self operator--()
	{
		if (_node == nullptr)
		{
			Node* cur = _root;
			while (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 = cur->_parent;
			while (parent&&parent->_left == cur)
			{
				cur = parent;
				parent = cur->_parent;
			}
			_node = parent;
		}
		return *this;
	}
	Ref operator*()
	{
		return _node->_data;
	}
	Ptr operator->()
	{
		return &_node->_data;
	}
	bool operator==(const Self& s )
	{
		return _node == s._node;
	}
	bool operator!=(const Self& s )
	{
		return _node != s._node;
	}
};

template<class K, class T,class KeyofT>
struct RBTree
{
	using Node = RBTreeNode<T>;
	typedef RBTreeIterator<T, T&, T*> Iterator;
	typedef RBTreeIterator<T, const T&, const T*> ConstIterator;
public:
	Iterator Begin()
	{
		Node* cur = _root;
		while (cur&&cur->_left)
		{
			cur = cur->_left;
		}
		return Iterator(cur,_root);
	}
	Iterator End()
	{
		return Iterator(nullptr, _root);
	}
	ConstIterator Begin()const
	{
		Node* cur = _root;
		while (cur&&cur->_left)
		{
			cur = cur->_left;
		}
		return Iterator(cur, _root);
	}
	ConstIterator End()const
	{
		return Iterator(nullptr, _root);
	}
	pair<Iterator,bool> Insert(const T& data)
	{
		KeyofT Kot;
		if (_root == nullptr)
		{
			_root = new Node(data);
			_root->_parent = nullptr;
			_root->_col = Black;
			return { Iterator(_root,_root) ,true};
		}
		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 { Iterator(cur,_root) ,false };
			}
		}
		cur = new Node(data);
		Node* newnode = cur;
		cur->_col = Red;
		if (Kot(parent->_data) > Kot(data))
		{
			parent->_left = cur;
		}
		else
		{
			parent->_right = cur;
		}
		cur->_parent = parent;
		while (parent&&parent->_col==Red)
		{
			Node* grandfather = parent->_parent;
			if (grandfather->_left == parent)
			{
				Node* uncle = grandfather->_right;
				if (uncle&&uncle->_col == Red)
				{
					grandfather->_col = Red;
					parent->_col = Black;
					uncle->_col = Black;
					cur = grandfather;
					parent = grandfather->_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)
				{
					grandfather->_col = Red;
					parent->_col = Black;
					uncle->_col = Black;
					cur = grandfather;
					parent = grandfather->_parent;
				}
				else
				{
					if (parent->_right==cur)
					{
						RotateL(grandfather);
						grandfather->_col = Red;
						parent->_col = Black;
					}
					else
					{
						RotateR(parent);
						RotateL(grandfather);
						grandfather->_col = Red;
						cur->_col = Black;
					}
					break;
				}
			}
		}
		_root->_col = Black;
		return { Iterator(newnode,_root) ,true };
	}
	~RBTree()
	{
		Destroy(_root);
	}
private:
	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;
			subL->_parent = nullptr;
		}
		else
		{
			if (pParent->_left == parent)
			{
				pParent->_left = subL;
			}
			else
			{
				pParent->_right = subL;
			}
			subL->_parent = pParent;
		}
	}
	void RotateL(Node* parent)
	{
		Node* subR = parent->_right;
		Node* subRL = subR->_left;
		parent->_right = subRL;
		if (subRL)
			subRL->_parent = parent;
		Node*pParent = parent->_parent;
		subR->_left = parent;
		parent->_parent = subR;
		if (pParent == nullptr)
		{
			_root = subR;
			subR->_parent = nullptr;
		}
		else
		{
			if (pParent->_left == parent)
			{
				pParent->_left = subR;
			}
			else
			{
				pParent->_right = subR;
			}
			subR->_parent = pParent;
		}

	}
	void Destroy(Node*root)
	{
		if (root == nullptr)
		{
			return;
		}
		Destroy(root->_left);
		Destroy(root->_right);
		delete root;
	}
	Node* Copy(Node* root)
	{
		if (root == nullptr)
		{
			return;
		}
		Node* newnode = new Node(root->_data);
		newnode->_left = Copy(root->_left);
		newnode->_right = Copy(root->_right);
		return newnode;
	}
	Node* _root = nullptr;
};

3.2 Myset.h

cpp 复制代码
#pragma once
#include"RBTree.h"
namespace KeyBreak
{
	template<class K>
	class Myset
	{
		struct KeyofMyset
		{
			const K& operator()(const K& Key)
			{
				return Key;
			}
		};
	public:
		typedef typename RBTree<K, const K, KeyofMyset>::Iterator iterator;
		typedef typename RBTree<K, const K, KeyofMyset>::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,KeyofMyset> _t;
	};
}

3.3 Mymap.h

cpp 复制代码
#pragma once
#include"RBTree.h"
namespace KeyBreak
{
	template<class K,class V>
	class Mymap
	{
		struct KeyofMap
		{
			const K& operator()(const pair<K, V>& kv)
			{
				return kv.first;
			}
		};
	public:
		typedef typename RBTree<K, pair<const K, V>, KeyofMap>::Iterator iterator;
		typedef typename RBTree<K, pair<const K, V>, KeyofMap>::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> tmp=_t.Insert({Key,V()});
			return tmp.first->second;
		}
	private:
		RBTree<K, pair<const K,V>,KeyofMap> _t;
	};
}

3.4 测试代码

test.cpp

运行结果如下(支持正序遍历,倒序遍历、插入、修改)

复制代码
#define _CRT_SECURE_NO_WARNINGS 1
#include"Myset.h"
#include"Mymap.h"
int main()
{
	KeyBreak::Myset<int> s;
	s.insert(2);
	s.insert(6);
	s.insert(5);
	s.insert(4);
	s.insert(1);
	KeyBreak::Myset<int>::iterator it= s.begin();
	while (it != s.end())
	{
		cout << *it << " ";
		++it;
	}
	cout << endl;
	KeyBreak::Myset<int>::iterator it2 = s.end();
	while (it2 != s.begin())
	{
		--it2;
		cout << *it2 << " ";
	}
	KeyBreak::Mymap<string, string> m;
	m.insert({ "left","左边" });
	m.insert({ "right","右边" });
	m.insert({ "sort","排序" });
	m["left"] = "剩余";
	m["insert"] = "插入";
	m["string"];
	cout << endl;
	KeyBreak::Mymap<string, string>::iterator it1 = m.begin();
	while (it1 != m.end())
	{
		cout << it1->first << " :"<<it1->second<<endl;
		++it1;
	}

}

文章结语

感谢你读到这里~我是「键盘敲碎了雾霭」,愿这篇文字帮你敲开了技术里的小迷雾 💻

如果内容对你有一点点帮助,不妨给个暖心三连吧👇

👍 点赞 | ❤️ 收藏 | ⭐ 关注

(听说三连的小伙伴,代码一次编译过,bug绕着走~)

你的支持,就是我继续敲碎技术雾霭的最大动力 🚀

🐶 小彩蛋:

复制代码
      /^ ^\
     / 0 0 \
     V\ Y /V
      / - \
    /    |
   V__) ||

摸一摸毛茸茸的小狗,赶走所有疲惫和bug~我们下篇见 ✨

相关推荐
zzj_2626101 小时前
实验七 Python 文件操作与异常处理
开发语言·python
LiLiYuan.1 小时前
【happens-before 八大规则详解】
java·开发语言
断点之下1 小时前
从C的struct到C++的class:封装、this指针、三大特性入门
开发语言·c++
yongui478341 小时前
基于稀疏低秩分解的图像去噪MATLAB实现
开发语言·matlab
誰能久伴不乏1 小时前
工业级 Modbus 上位机架构:基于滴答引擎与状态锁的高并发调度器
c++·qt·架构
geovindu1 小时前
python: N-Barrier Pattern
开发语言·python·设计模式·屏障模式
战族狼魂2 小时前
MetaPrompt编译器核心逻辑拆解
开发语言·人工智能·python
gihigo19982 小时前
MATLAB实现光谱特征波长提取
开发语言·matlab
代钦塔拉2 小时前
Qt信号槽参数类型全解:原生类型、结构体、enum class强枚举注册与传参实战
开发语言·qt