从零开始的C++生活——第十六讲

这一讲我要以红黑树为底层,封装模拟实现一个自己的mapset出来。

这里我将频繁使用模板,参考C++源码写出来一份类似的我们自己的map\set。

其实你仔细想想,map、set差异并不大,无非就是一个keyvalue结构,一个key结构,底层逻辑什么插入删除查询什么的都是一样的,有不同的点也就是map支持\[\]运算符,但其实有了map的学习,\[\]也就是调用的insert对吧,所以你甚至都不需要再写一个单独的逻辑出来,直接复用插入就好,map还支持修改,但是修改也就是复用了find查询对吧,所以大体上二者没什么差异,那就完全没必要写两个逻辑在我们程序员的角度说,根本不需要手动实现两颗红黑树。

模板这时候就派上用场了,虽然我们不手动实现两颗红黑树,但你要想实现mapset还真的就是需要两颗红黑树,这时候,我需要交给编译器自行实现,因此,我们只需要一个模板基类,传对应的参数即可。

mapset都是红黑树,他们的节点最大差异是什么?是里边存储的类型,所以针对红黑树节点的设计,我们就以此为模板参数,不用考虑什么底层是pair还是key什么的,你直接一个T传过去就好。

cpp 复制代码
//T代表的就是<key,value>
template<class T>
struct RBTreeNode
{

	RBTreeNode(T data)
		:_data(data)
		, _left(nullptr)
		, _right(nullptr)
		, _parent(nullptr)
		, _col(RED)
	{

	}

	T _data;
	RBTreeNode<T>* _left = nullptr;
	RBTreeNode<T>* _right = nullptr;
	RBTreeNode<T>* _parent = nullptr;
	color _col;

};

然后关于红黑树的基类逻辑,说实话,没有怎么改,基本上就是改了一下类型。

有几个比较大的变化,第一你想一下,传参应该传什么模板参数?

源码中是key,<key,value>后边还有,但这个一会才能讲到。

为啥要穿两个key?思考一下,map你直接传一个pair的话单看map没有任何问题,但是,你拿到key的方式是通过pair的first,如果是set,他又pair吗?他能这么拿到key吗?为了代码的复用性,我们就不要采取上述模式只传一个<key,value>。

好的,那我们简单来看一看mapset的大体结构

cpp 复制代码
template<class T>
class myset
{
	
private:
	RBTree<T, T, KeyOfSet> _set;


};
cpp 复制代码
//这个K是key V是value
template<class K,class V>
class mymap
{
	
private:
	RBTree<K, pair<const K, V>, KeyOfMap> _map;
};

对于我们自己来说,你想怎么写就怎么写了,key就是key,value就是value。

接下来看一看插入的逻辑。

大体上跟上一讲红黑树没什么区别。

需要注意的点,第一由于泛型的存在,在你插入之前进行得比较环节需要特殊处理,首先set你不用管,map你需要注意,pair底层支持比较,但比较逻辑不是我们想要的,他的比较逻辑是key相同再往下比value,我们其实只希望比较key,因此第三个模板参数是一个仿函数,用来拿到对应的比较的变量。

cpp 复制代码
struct KeyOfSet
{
	const T& operator()(const T& t)
	{
		return t;
	}
};
cpp 复制代码
struct KeyOfMap
{

	const K& operator()(const pair<K,V>& t)
	{
		return t.first;
	}

};

其他的真的没啥可注意的了

cpp 复制代码
pair<Iterator, bool> Insert(const T data)
{
	Node* cur = _root;
	Node* parent = nullptr;
	KeyOfT kot;
	while (cur)
	{
		if (kot(data) > kot(cur->_data))
		{
			//在右边找
			parent = cur;
			cur = cur->_right;
		}
		else if (kot(data) < kot(cur->_data))
		{
			//在左边找
			parent = cur;
			cur = cur->_left;
		}
		else
		{
			return { Iterator(cur,_root),false };
		}
	}
	cur = new Node(data);
	Node* newnode = cur;
	//空树
	if (parent == nullptr)
	{
		_root = cur;
		_root->_col = BLACK;
		return { Iterator(_root,_root),true };
	}
	else
	{
		if (kot(parent->_data) < kot(data))
		{
			//右边
			parent->_right = cur;
			cur->_parent = parent;
		}
		else if (kot(parent->_data) > kot(data))
		{
			//左边
			parent->_left = cur;
			cur->_parent = parent;
		}
		else
		{
			assert(false);
		}
		Node* grandfather = nullptr;
		Node* uncle = nullptr;
		while (parent)
		{
			grandfather = parent->_parent;
			if (grandfather)
			{
				if (grandfather->_left == parent)
				{
					uncle = grandfather->_right;
				}
				else if (grandfather->_right == parent)
				{
					uncle = grandfather->_left;
				}
				else
				{
					assert(false);
				}
			}
			else
			{
				uncle = nullptr;
			}
			if (parent->_col == BLACK)
				break;
			//cur在parent的左边插入(右单旋的情况)
			if (cur == parent->_left)
			{
				//只要uncle存在grandfather就一定不为空
				if (uncle && uncle->_col == RED)
				{
					//parent变黑
					//uncle变黑
					//grandfather变红
					uncle->_col = parent->_col = BLACK;
					grandfather->_col = RED;
					cur = grandfather;
					parent = cur->_parent;
				}
				else if ((uncle && uncle->_col == BLACK) || (uncle == nullptr))
				{
					if (grandfather)
					{
						//cur插入在parent的左边
						if (parent == grandfather->_left)
						{
							//右单旋
							RotateR(grandfather);
							grandfather->_col = RED;
							parent->_col = BLACK;
						}
						else if (parent == grandfather->_right)
						{
							//双旋
							RotateR(parent);
							RotateL(grandfather);
							cur->_col = BLACK;
							grandfather->_col = RED;
						}
					}
					else
					{
						parent->_col = BLACK;
					}

					break;
				}
				else
				{
					assert(false);
				}
			}
			//cur在parent的右边插入
			else if (cur == parent->_right)
			{
				//只要uncle存在grandfather就一定不为空
				if (uncle && uncle->_col == RED)
				{
					//parent变黑
					//uncle变黑
					//grandfather变红
					uncle->_col = parent->_col = BLACK;
					grandfather->_col = RED;
					cur = grandfather;
					parent = cur->_parent;
				}
				else if ((uncle && uncle->_col == BLACK) || (uncle == nullptr))
				{
					if (grandfather)
					{
						//cur插入在parent的左边
						if (parent == grandfather->_right)
						{
							//右单旋
							RotateL(grandfather);
							grandfather->_col = RED;
							parent->_col = BLACK;
						}
						else if (parent == grandfather->_left)
						{
							//双旋
							RotateL(parent);
							RotateR(grandfather);
							cur->_col = BLACK;
							grandfather->_col = RED;
						}
					}
					else
					{
						parent->_col = BLACK;
					}

					break;
				}
				else
				{
					assert(false);
				}

			}


		}

	}
	_root->_col = BLACK;
	return { Iterator(newnode,_root),true };
}

这里的返回值我们还是依照前面map的实现章节,用来适应operator\[\]运算符的。

不过,当我们搞出来一个mapset后,中序遍历的逻辑就没用的,我们反而需要的是一步一步利用迭代器遍历,迭代器我们也需要模拟实现一个出来。

迭代器需要传什么参数?

其实为了适用于operator->和operator*,我们在list就讲过用一个<T,Ref,Ptr>的方式,分别传<key,value>,T&,T*。

cpp 复制代码
template<class T,class Ref,class Ptr>
struct Iterator
{

	typedef RBTreeNode<T> Node;
	typedef Iterator<T, Ref, Ptr> Self;


	Iterator(Node* node, Node* root)
		:_node(node)
		, _root(root)
	{

	}

	Node* _node;
	Self operator--()
	{
		
	}
	Self operator++()
	{
		
	}
	Ptr operator->()
	{
		return &_node->_data;
	}
	Ref operator*()
	{
		return _node->_data;
	}
	bool operator==(const Self& s)
	{
		return _node == s._node;
	}
	bool operator!=(const Self& s)
	{
		return _node != s._node;
	}


};

其他的什么==什么!=这种我都不说了,难搞的其实就是++--逻辑。

++逻辑在搜索树里边咋实现?

还是按照中序遍历的顺序操作。

但你怎么判断该找那个节点又是个麻烦问题。

分情况,第一,如果右子树不为空,你这时候++应该怎么加?此时cur节点相当于一个根,接下来应该便利的是右子树的最左端。

所以你拿到右子树根节点后一路向左即可。

cpp 复制代码
//右子树不为空找右子树最左节点
if (_node->_right)
{
	cur = cur->_right;
	while (cur->_left)
	{
		cur = cur->_left;
	}
	_node = cur;
	return *this;
}

那右子树为空呢?

说明当前你这颗子树(以cur为根)已经遍历完成,该往上找了。

怎么找?其实同样的道理,如果你cur本身也是父亲节点的右子树,那说明父亲节点为根的树也遍历完了,接着找祖先以此类推,只有当祖先节点是他的上一层节点的左节点的时候,才需要遍历此时的根节点然后接着遍历右子树。

还有情况是你直接走到根节点了,那就遍历完了,cur本身就是最末节点。

cpp 复制代码
//右子树为空,找第一个为祖先左孩子的祖先节点
else
{
	while (cur->_parent && cur != cur->_parent->_left)
	{
		cur = cur->_parent;
	}
	_node = cur->_parent;
	return *this;
}

++实现好了,--其实就是反着来。

cpp 复制代码
Self operator--()
{
	Node* cur = _node;
	if (_node == nullptr)
	{
		cur = _root;
		while (cur->_right)
		{
			cur = cur->_right;
		}
		_node = cur;
		return *this;
	}
	//左子树不为空找左子树最右节点
	if (_node->_left)
	{
		cur = cur->_left;
		while (cur->_right)
		{
			cur = cur->_right;
		}
		_node = cur;
		return *this;
	}
	else
	{
		while (cur->_parent && cur != cur->_parent->_right)
		{
			cur = cur->_parent;
		}
		_node = cur->_parent;
		return *this;
	}

}

但是但是,如果你走到空了,也就是遍历完了,这时候再减,其实也就是想拿到最末节点对吧,那你就需要搞一个最末节点出来,这时候需要根节点一直向右,所以成员变量还需要一个root.

cpp 复制代码
Node* _root;

好,那么对应到我们的红黑树里边,需要实现什么接口呢?

其实也就是begin和end

begin的逻辑其实就是最左节点,你一直从根节点开始找左孩子,不为空的最后一个就是。

关于end,其实这里就是空啊,因为左闭右开你不能取到最后一个节点。

cpp 复制代码
public:
	typedef RBTreeNode<T> Node;
	typedef Iterator<T, const T&, const T*> Const_Iterator;
	typedef Iterator<T, T&, T*> Iterator;

public:
	Const_Iterator Begin() const
	{
		Node* cur = _root;
		while (cur && cur->_left)
		{
			cur = cur->_left;
		}
		return Const_Iterator(cur, _root);
	}
	Const_Iterator End() const
	{
		return Const_Iterator(nullptr, _root);
	}
	Iterator Begin()
	{
		Node* cur = _root;
		while (cur && cur->_left)
		{
			cur = cur->_left;
		}
		return Iterator(cur, _root);
	}
	Iterator End()
	{
		return Iterator(nullptr, _root);
	}

那么对应到mapset里呢?

cpp 复制代码
public:
	typedef typename RBTree<T, T, KeyOfSet>::Const_Iterator const_iterator;
	typedef typename RBTree<T, T, KeyOfSet>::Iterator iterator;
	

public:
	const_iterator cbegin() const
	{
		return _set.Begin();
	}
	const_iterator cend() const
	{
		return _set.End();
	}
	iterator begin()
	{
		return _set.Begin();
	}
	iterator end()
	{
		return _set.End();
	}
cpp 复制代码
public:
	typedef Iterator<pair<const K, V>, const pair<const K, V>&, const pair<const K, V>*> const_iterator;
	typedef Iterator<pair<const K, V>, pair<const K, V>&, pair<const K, V>*> iterator;
public:
	const_iterator cbegin() const
	{
		return _map.Begin();
	}
	const_iterator cend() const
	{
		return _map.End();
	}
	iterator begin()
	{
		return _map.Begin();
	}
	iterator end()
	{
		return _map.End();
	}

所有的逻辑都已经实现差不多了,我们来跑一组测试用例。

cpp 复制代码
int main()
{
	ds::myset<int> my_set;
	my_set.Insert(16);
	my_set.Insert(241);
	my_set.Insert(11);
	my_set.Insert(31);
	my_set.Insert(10);
	for (auto e : my_set)
	{
		cout << e << " ";
	}
	cout << endl;
	ds::mymap<string, string> my_map;
	my_map.Insert({ "sdf","saf" });
	my_map.Insert({ "dhds","aa" });
	my_map.Insert({ "nbh","qi" });
	my_map.Insert({ "ppu","cz" });
	my_map.Insert({ "asiu","zjlkx" });

	for (auto e : my_map)
	{
		cout << e.first << ":" << e.second << endl;
	}
	cout << endl;

	my_map["aaa"];
	my_map["ccc"] = "aaa";
	my_map["bbb"] = "aaa";
	my_map["ddd"] = "aaa";
	my_map["eee"] = "aaa";
	for (auto e : my_map)
	{
		cout << e.first << ":" << e.second << endl;
	}
	cout << endl;


	ds::mymap<string, string>::const_iterator it1 = my_map.cbegin();
	ds::mymap<string, string>::const_iterator it2 = my_map.cend();
	while (it1 != it2)
	{
		--it2;
		cout << (*it2).first << ":" << (*it2).second << endl;
	}


	return 0;
}

好的那么关于这一讲就讲到这里了,下一讲开始讲解哈希。

相关推荐
两点王爷29 分钟前
StringBuffer 和 StringBuilder 高频面试题全解析
java·开发语言·面试
Pin_Qing33 分钟前
优惠期结束与计费周期更迭:Gemini 4 Carbon/Argon 价格调整后的架构应对
大数据·开发语言·人工智能·程序人生·架构
沫璃染墨37 分钟前
《Qt从零入门系列(十七):网络编程基础详解——从Socket原理到TCP/UDP通信API》
开发语言·网络·c++·qt·http·qt5·qt6.3
金榜题名萱38 分钟前
蓝桥杯|石子合并(区间动态规划)
c语言·数据结构·c++·算法·蓝桥杯·动态规划
SummerJokes40 分钟前
Java 异常处理完整详解|try‑catch‑finally、throws、throw、自定义异常实战
java·开发语言·python
ShineWinsu1 小时前
对于Qt:绘图的解析
开发语言·数据库·c++·qt·面试·客户端·绘图
骑着蜗牛撵大象3271 小时前
红外太阳能板缺陷检测:三端推理与数据集自动标注落地
开发语言·python·小程序·pyqt·yolov8·自动标注·红外缺陷检测
纪念 2291 小时前
C++ 算法模板与错题 (前缀和)
开发语言·c++·算法
sharemylove1 小时前
Java 面向对象(OOP)笔记
java·开发语言·笔记·学习·课程设计