C++ map和set模拟实现

本文详细介绍了如何改造红黑树以适应map和set的需求,包括添加仿函数处理键比较、改造插入函数以支持set和map的K/V操作,以及实现迭代器的++和--操作。
摘要由CSDN通过智能技术生成

💓博主CSDN主页:麻辣韭菜💓

⏩专栏分类:C++知识分享

🚚代码仓库:C++高阶🚚

🌹关注我🫵带你学习更多C++知识
  🔝🔝


 


目录

前言

改造红黑树节点

 改造红黑树

仿函数

 插入函数改造

迭代器 

 ++ -- 重载

​编辑

迭代器再次改造插入函数 

 map【】重载


 

前言

前面我们实现了红黑树,本篇就讲map和set的底层是怎么用红黑树来进行封装的!!!

我们要模拟实现map和set需要改造之前的红黑树,因为set只有一个K,而我们的红黑树模板参数是2个一个T和一个V。

改造红黑树节点

enum Color
{
	RED,
	BLACK,
};

template<class T>
struct RBTreeNode
{
	RBTreeNode<T>* _left;
	RBTreeNode<T>* _right;
	RBTreeNode<T>* _parent;
	T _data;
	Color _col;

	RBTreeNode(const T& data)
		:_left(nullptr)
		, _right(nullptr)
		, _parent(nullptr)
		, _data(data)
		, _col(RED) //为什么默认是红色?根节点必须是黑色,这就意味着默认给黑色那么调整次数就会变多。
	{}
};

 改造红黑树

我们先来看看stl源码中map和set是怎么定义的 

 

这样设计就很完美 你用set 两个都是K,我们只需要拿第一个K,你用map 第一个是K,第二个是V。

这里就问题了,插入比较大小时,按照原来的红黑树来说,只能是map兼容。set不行。

我们可以加仿函数,set返回它的K,map返回它的first。 当然这里插入函数也是要改造的。

仿函数

#pragma once
#include "RBTree.h"

namespace gx
{
	template <class K, class V>
	class map
	{
		struct MapKeyofT
		{
			const K& operator()(const pair<const K, V>& kv)
			{
				return kv.first;
			}
		};
    private:
	RBTree<K, pair<const K, V>, MapKeyOfT> _t;
	};
}

#pragma once
#include "RBTree.h"


namespace gx
{
	template<class K>
	class set
	{
		struct SetKeyofT
		{	
			const K& operator()(const K& key)
			{
				return  key;
			}
		};
	private:
		RBTree<K, K, SetKeyofT> _t;
	};
}

template <class K, class T, class KeyofT>
class RBTree
{
	typedef RBTreeNode<T> Node;
private:
	Node* _root = nullptr;
};

 

最后用一张图来说明它们三个之间的关系!!! 

 插入函数改造

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);
		//判断k的值是大于还是小于父亲的k值
		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;
				// 情况1:u存在且为红,变色处理,并继续往上处理
				if (uncle && uncle->_col == RED)
				{
					parent->_col = BLACK;
					uncle->_col = BLACK;
					grandfather->_col = RED;

					// 继续往上调整
					cur = grandfather;
					parent = cur->_parent;
				}
				else // 情况2+3:u不存在/u存在且为黑,旋转+变色
				{
					//     g
					//   p   u
					// c 
					if (cur == parent->_left)
					{
						RotateR(grandfather);
						parent->_col = BLACK;
						grandfather->_col = RED;
					}
					else
					{
						//     g
						//   p   u
						//     c
						RotateL(parent);
						RotateR(grandfather);
						cur->_col = BLACK;
						//parent->_col = RED;
						grandfather->_col = RED;
					}

					break;
				}
			}
			else // (grandfather->_right == parent)
			{
				//    g
				//  u   p
				//        c
				Node* uncle = grandfather->_left;
				// 情况1:u存在且为红,变色处理,并继续往上处理
				if (uncle && uncle->_col == RED)
				{
					parent->_col = BLACK;
					uncle->_col = BLACK;
					grandfather->_col = RED;

					// 继续往上调整
					cur = grandfather;
					parent = cur->_parent;
				}
				else // 情况2+3:u不存在/u存在且为黑,旋转+变色
				{
					//    g
					//  u   p
					//        c
					if (cur == parent->_right)
					{
						RotateL(grandfather);
						grandfather->_col = RED;
						parent->_col = BLACK;
					}
					else
					{
						//    g
						//  u   p
						//    c
						RotateR(parent);
						RotateL(grandfather);
						cur->_col = BLACK;
						grandfather->_col = RED;
					}

					break;
				}
			}
		}

		_root->_col = BLACK;

		return true;
	}

运行没有问题,同时兼容set和map问题解决了,接下来就是要实现迭代器。我们先实现红黑树的迭代器。 

迭代器 

我们构建一个迭代器的类 然后再红黑树这个类里面 typedef 这个迭代器类

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

* 、->、 != 这三个运算符重载很好写关键是++和-- 这个两个有点复杂,直接给代码cpu直接干烧。我们画图理解 

 

 ++ -- 重载

 这里以++举例 

self& operator++()
	{
		if (_node->_right)
		{
			//如果右不为空那么右的左孩子一定比右这个根节点小
			Node* subLeft = _node->_right;
			while (subLeft->_left)
			{
				subLeft = subLeft->_left;
			}
			_node = subLeft;
		}
		else
		{
			//如果右为空,说明该节点的左右子树已经遍历完了,这时我们就要往上找它的父亲的父亲,并且父亲还是爷爷的左子树
			Node* cur = _node;
			Node* parent = cur->_parent;
			while (parent && parent->_right == cur) //当条件不满足的时候说明父亲就是爷爷左子树
			{
				cur = parent;
				parent = parent->_parent;
			}
			//循环结束说明我们已经找到了这时在把值赋值给_node
			_node = parent;
		}
	}
};
self& operator--()
	{
		if (_node->_left)
		{
			//如果左不为空那么左的右孩子一定比左这个根节点大
			Node* subRight = _node->_left;
			while (subRight->_right)
			{
				subRight = subRight->_right;
			}
			_node = subRight;
		}
		else
		{
			//如果左为空,说明该节点的左右子树已经遍历完了,这时我们就要往上找它的父亲的父亲,并且父亲还是爷爷的右子树
			Node* cur = _node;
			Node* parent = cur->_parent;
			while (parent && parent->_left == cur) //当条件不满足的时候说明父亲就是爷爷右子树
			{
				cur = parent;
				parent = parent->_parent;
			}
			//循环结束说明我们已经找到了这时在把值赋值给_node
			_node = parent;
		}
	}

我们先用封装set


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*> const_iterator;
	iterator begin()
	{
		Node* cur = _root;
		while (cur && cur->_left)
		{
			cur = cur->_left
		}
		return iterator(cur);
	}
	iterator end()
	{
		return iterator(nullptr);
	}

 验证一下写的对不对

我们再封装map

namespace gx
{
	template <class K, class V>
	class map
	{
		struct MapkeyofT
		{
			const K& operator()(const pair<const K, V>& kv)
			{
				return kv.first;
			}
		};
	public:
		typedef typename RBTree<K, pair<const K, V>, MapkeyofT>::iterator iterator;
		
		iterator begin()
		{
			return _t.begin();
		}
		iterator end()
		{
			return _t.end();
		}
		bool insert(const pair<const K,V>& kv)
		{
			return _t.Insert(kv);
		}

	private:
		RBTree<K, pair<const K, V>, MapkeyofT> _t;
	};
	void test_map1()
	{
		int a[] = { 16, 3, 7, 11, 9, 26, 18, 14, 15 };
		map<int, int> m;
		for (auto e : a)
		{
			m.insert(make_pair(e, e));
		}
		map<int, int>::iterator it = m.begin();
		while (it != m.end())
		{
			cout << it->first << ":" << it->second << endl;
			++it;
		}
		cout << endl;
	}
}

但是这里就有个问题 set 我们是可以修改的,我们需要再对迭代器再进行优化,让set不能修改。

我们来看看源码是怎么写的 

 

 我们可以看到源码的set 普通迭代器和const迭代器都是用的红黑树的const的迭代器。

 那我们也把自己set迭代器都改成const迭代器

namespace gx
{
	template<class K>
	class set
	{

		struct SetKeyofT
		{	
			const K& operator()(const K& key)
			{
				return  key;
			}
		};
	public:
		typedef typename RBTree<K, K, SetKeyofT>::const_iterator iterator;
		typedef typename RBTree<K, K, SetKeyofT>::const_iterator const_iterator;
		iterator begin()
		{
			return _t.begin();
		}
		iterator end()
		{
			return _t.end();
		}
		bool insert(const K& key)
		{
			return _t.Insert(key);
		}


	private:
		RBTree<K, K, SetKeyofT> _t;
	};

 

这时就出问题了,普通迭代器的参数没有办法转换成const迭代器。怎么解决?

 在迭代器类 加上这段代码

_RBTreeiterator(const _RBTreeiterator<T,  T&,  T*>& it)
		:_node(it._node)
	{}

 如何理解这段代码


1、typedef __RBTreeIterator<T, T&, T*> itertaor; 拷贝构造

2、 typedef __RBTreeIterator<T, const T&, const T*> const_itertaor;支持普通迭代器构造const迭代器的构造函数

迭代器再次改造插入函数 

源码的map和set是支持迭代器插入,而我们的之前的返回类型是bool明显不支持

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;
		//判断k的值是大于还是小于父亲的k值
		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;
				// 情况1:u存在且为红,变色处理,并继续往上处理
				if (uncle && uncle->_col == RED)
				{
					parent->_col = BLACK;
					uncle->_col = BLACK;
					grandfather->_col = RED;

					// 继续往上调整
					cur = grandfather;
					parent = cur->_parent;
				}
				else // 情况2+3:u不存在/u存在且为黑,旋转+变色
				{
					//     g
					//   p   u
					// c 
					if (cur == parent->_left)
					{
						RotateR(grandfather);
						parent->_col = BLACK;
						grandfather->_col = RED;
					}
					else
					{
						//     g
						//   p   u
						//     c
						RotateL(parent);
						RotateR(grandfather);
						cur->_col = BLACK;
						//parent->_col = RED;
						grandfather->_col = RED;
					}

					break;
				}
			}
			else // (grandfather->_right == parent)
			{
				//    g
				//  u   p
				//        c
				Node* uncle = grandfather->_left;
				// 情况1:u存在且为红,变色处理,并继续往上处理
				if (uncle && uncle->_col == RED)
				{
					parent->_col = BLACK;
					uncle->_col = BLACK;
					grandfather->_col = RED;

					// 继续往上调整
					cur = grandfather;
					parent = cur->_parent;
				}
				else // 情况2+3:u不存在/u存在且为黑,旋转+变色
				{
					//    g
					//  u   p
					//        c
					if (cur == parent->_right)
					{
						RotateL(grandfather);
						grandfather->_col = RED;
						parent->_col = BLACK;
					}
					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);;
	}

 这时set插入函数也是需要改

 

pair<iterator, bool>  insert(const K& key)
		{
			return _t.Insert(key);
		}

 map【】重载

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

 

 封装到这里就结束了,其他的插入和删除4个默认函数都是比较简单的,这里博主就不在细讲了,我们理解底层原理就行不要较真 前人已经给我们造好轮子了,我们就不要深究了。

代码 为了方面大家阅读,我做了拆分,完整代码大家可以去看我码云,码云在顶页有链接

下期预告:

哈希

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值