【C++ —— 用一棵红黑树同时封装出map和set】

总览

RBTree

enum Colour
{
    RED,
    BLACK
};

// RBTree节点
template<class T>
struct RBTreeNode
{
    RBTreeNode<T>* _left;
    RBTreeNode<T>* _right;
    RBTreeNode<T>* _parent;
    Colour _col;
    T _data;

    RBTreeNode(const T& data)
        : _left(nullptr), _right(nullptr), _parent(nullptr), _col(RED), _data(data)
    {}
};

// RBTree迭代器
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*();
    Ptr operator->();
    bool operator!=(const Self& s);
    Self& operator++();
};

// RBTree实现
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;
    RBTree(const RBTree<K, T, KeyOfT>& t);
    ~RBTree();
    RBTree<K, T, KeyOfT>& operator=(RBTree<K, T, KeyOfT> t);

    Iterator Begin();
    Iterator End();
    ConstIterator Begin() const;
    ConstIterator End() const;
    Iterator Find(const K& key);
    std::pair<Iterator, bool> Insert(const T& data);
    
    void RotateR(Node* parent);
    void RotateL(Node* parent);
    void InOrder();
    bool IsBalance() const;

private:
    Node* Copy(Node* root);
    void Destroy(Node* root);
    bool Check(Node* root, int blackNum, const int refNum) const;
    void _InOrder(Node* root) const;

    Node* _root = nullptr;
};

MyMap

namespace qq
{
	template<class K, class V>
	class map
	{
		struct MapKeyOfT
		{
			const K& operator()(const std::pair<K, V>& kv);
		};
	public:
		typedef typename RBTree<K, std::pair<const K, V>, MapKeyOfT>::Iterator iterator;
		typedef typename RBTree<K, const std::pair<K, V>, MapKeyOfT>::ConstIterator const_iterator;

		const_iterator begin() const;
		const_iterator end() const;
		iterator begin();
		iterator end();
		iterator find(const K& key);
		std::pair<iterator, bool> insert(const std::pair<K, V>& kv);
		V& operator[](const K& key);

	private:
		RBTree<K, std::pair<const K, V>, MapKeyOfT> _t;
	};
}

MySet

namespace qq
{
	template<class K>
	class set
	{
		struct SetKeyOfT
		{
			const K& operator()(const K& key);
		};
	public:
		typedef typename RBTree<K, const K, SetKeyOfT>::Iterator iterator;
		typedef typename RBTree<K, const K, SetKeyOfT>::ConstIterator const_iterator;

		const_iterator begin() const;
		const_iterator end() const;
		iterator begin();
		iterator end();
		iterator find(const K& key);
		std::pair<iterator, bool> insert(const K& key);

	private:
		RBTree<K, const K, SetKeyOfT> _t;
	};
}

红黑树源代码

enum Colour
{
	RED,
	BLACK
};

template<class K, class V>
struct RBTreeNode
{
	RBTreeNode<K, V>* _left;
	RBTreeNode<K, V>* _right;
	RBTreeNode<K, V>* _parent;

	pair<K, V> _kv;
	Colour _col;

	RBTreeNode(const pair<K, V>& kv)
		:_left(nullptr)
		, _right(nullptr)
		, _parent(nullptr)
		, _kv(kv)
		, _col(RED)
	{}
};

template<class K, class V>
class RBTree
{
	typedef RBTreeNode<K, V> Node;
public:
	bool Insert(const pair<K, V>& kv)
	{
		if (_root == nullptr)
		{
			_root = new Node(kv);
			_root->_col = BLACK;
			return true;
		}

		Node* parent = nullptr;
		Node* cur = _root;
		while (cur)
		{
			if (cur->_kv.first < kv.first)
			{
				parent = cur;
				cur = cur->_right;
			}
			else if (cur->_kv.first > kv.first)
			{
				parent = cur;
				cur = cur->_left;
			}
			else
			{
				return false;
			}
		}

		cur = new Node(kv);
		cur->_col = RED; // 新增节点给红色
		if (parent->_kv.first < kv.first)
		{
			parent->_right = cur;
		}
		else
		{
			parent->_left = cur;
		}
		cur->_parent = 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 = 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 = uncle->_col = BLACK;
					grandfather->_col = RED;

					// 继续往上处理
					cur = grandfather;
					parent = cur->_parent;
				}
				else // 叔叔不存在,或者存在且为黑
				{
					// 情况二:叔叔不存在或者存在且为黑
					// 旋转+变色
					//      g
					//   u     p
					//            c
					if (cur == parent->_right)
					{
						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 true;
	}

	void RotateR(Node* parent)
	{
		Node* subL = parent->_left;
		Node* subLR = subL->_right;

		parent->_left = subLR;
		if (subLR)
			subLR->_parent = parent;

		subL->_right = 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->_parent = parent;

		subR->_left = parent;
		Node* ppNode = parent->_parent;

		parent->_parent = subR;

		if (parent == _root)
		{
			_root = subR;
			_root->_parent = nullptr;
		}
		else
		{
			if (ppNode->_right == parent)
			{
				ppNode->_right = subR;
			}
			else
			{
				ppNode->_left = subR;
			}
			subR->_parent = ppNode;
		}
	}

	void InOrder()
	{
		_InOrder(_root);
		cout << endl;
	}

	bool IsBalance()
	{
		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:
	bool Check(Node* root, int blackNum, const int refNum)
	{
		if (root == nullptr)
		{
			//cout << blackNum << endl;
			if (refNum != blackNum)
			{
				cout << "存在黑色节点的数量不相等的路径" << endl;
				return false;
			}

			return true;
		}

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

private:
	Node* _root = nullptr;
	//size_t _size = 0;
};

红黑树模板参数的控制

因为set是K模型的容器,而map是KV模型的容器,我们上面实现的红黑树是KV模型的红黑树,那怎么去使用KV的红黑树来同时实现setmap呢?
这里我们就需要更改红黑树的模板参数了,讲红黑树的第二个模板参数更改为T

template<class K, class T>
class RBTree

当我们模拟实现set时,只需控制T传入Key,如果模拟实现map时,则需要给T传入K 和 V。
如下图:
在这里插入图片描述

为什么要保留第一个模板参数是K?

我们可以通过第二个模板参数T来决定传入的是K还是KV,那为什么还要保留第一个K?

例如,在 Find函数中,你需要传入一个键值来查找相应的元素。由于键的类型可能与存储的值类型不同,单独保存键的类型允许你灵活地处理不同的键类型。
示例:如果你的树存储的是 std::pair<int, std::string>,但你想用 int 作为键来查找元素,那么你需要K作为键的类型。K 允许 RBTree 区分存储的实际数据类型和用作索引的键类型。

模板参数中仿函数的增加

因为我们现在不知道红黑树代码模板的第二个参数传入的是K还是pair,所以在后续的操作(比如比大小等)时会出现问题,所以这里我们使用一个仿函数来达到取值的目的。

如果是set,那么这里的仿函数则直接返回第二个模板参数的k即可。
如果是map,那么这里的仿函数则根据map的取值规则,返回pair<k,v>k即可。

仿函数是重载运算符(),通过对象调用函数来是使用。具体的仿函数可以参考这篇博客priority_queue的模拟实现

class set
{
	struct SetKeyOfT
	{
		const K& operator()(const K& key)
		{
			return key;
		}
	};
}

class map
{
	struct MapKeyOfT
	{
		const K& operator()(const pair<K, V>& kv)
		{
			return kv.first;
		}
	};
}

迭代器模拟

 在红黑树中,迭代器是访问和遍历树节点的关键工具。下面将介绍红黑树迭代器的实现,包括如何通过迭代器遍历节点、解引用节点,以及判断两个迭代器是否相等。我们将详细讲解每个操作的实现细节,来更好理解如何高效地操作红黑树中的元素。

1. 迭代器的定义和结构

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)
    {}
    // 各种操作符重载
};

  • 模板参数

    • T:表示树节点存储的数据类型。
    • Ref:引用类型,用于 operator* 的返回类型。
    • Ptr:指针类型,用于 operator-> 的返回类型。
      成员变量:
  • _node:当前迭代器指向的节点。

2. 迭代器的操作符重载

解引用操作符 operator 和箭头操作符 operator->*

Ref operator*()
{
    return _node->_data;
}

Ptr operator->()
{
    return &_node->_data;
}

  • operator* 返回当前节点的引用,允许直接访问节点数据。
  • operator-> 返回当前节点数据的指针,允许通过指针访问节点数据成员。

不等于操作符 operator!=

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

  • 用于比较两个迭代器是否指向不同的节点。

前置递增操作符 operator++
前置递增操作符 operator++ 在红黑树迭代器中用于移动到下一个节点。其目的是实现节点的遍历,确保能够按顺序访问树中的元素。红黑树的迭代器在实现这个操作符时需要处理两种主要情况:

  • 如果节点有右子树: 如果当前节点 _node 有右子节点,则下一个节点是其右子树中的最左子节点。
  • 如果节点没有右子树: 如果当前节点没有右子节点,向上追溯父节点直到当前节点是其父节点的左子节点,那个父节点即为后继节点。

图示讲解
假设我们有如下二叉搜索树:

示例 1:节点有右子树
假设当前节点是 6

  1. 节点 6 有右子树。
  2. 找右子树的最左节点,即节点 7。
  3. 因此,节点 6 的后继节点是 7。

示例 2:节点没有右子树
假设当前节点是 5

  1. 节点 5 没有右子树。
  2. 向上追溯父节点:
  • 当前节点 5 是其父节点 3 的右子节点。
  • 继续向上追溯,节点 3 是其父节点 6 的左子节点。
  • 因此,节点 6 是节点 5 的后继节点。
    在这里插入图片描述

代码:

Self& operator++()
{
    if (_node->_right)
    {
        Node* leftMin = _node->_right;
        while (leftMin->_left)
        {
            leftMin = leftMin->_left;
        }

        _node = leftMin;
    }
    else
    {
        Node* cur = _node;
        Node* parent = cur->_parent;
        while (parent && cur == parent->_right)
        {
            cur = parent;
            parent = parent->_parent;
        }

        _node = parent;
    }
    return *this;
}

set模拟

我们使用红黑树来封装set,在红黑树的基础上,我们只需要对其进行简单的封装即可完成set的简单模拟。

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;

		const_iterator begin() const
		{
			return _t.Begin();
		}

		const_iterator end() const
		{
			return _t.End();
		}

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

		iterator end()
		{
			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;
	};

map模拟

map的实现也与set的实现类似,但注意仿函数的实现即可。

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, const K, MapKeyOfT>::ConstIterator const_iterator;

		const_iterator begin() const
		{
			return _t.Begin();
		}

		const_iterator end() const
		{
			return _t.End();
		}

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

		iterator end()
		{
			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;
	};

代码

红黑树的代码

#pragma once
#include<vector>

enum Colour
{
	RED,
	BLACK
};

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

	Colour _col;
	T _data;

	RBTreeNode(const T& data)
		:_left(nullptr)
		, _right(nullptr)
		, _parent(nullptr)
		, _col(RED)
		, _data(data)
	{}
};

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++()
	{
		if (_node->_right)
		{
			//下一个是右数的最左节点
			Node* leftMin = _node->_right;
			while (leftMin->_left)
			{
				leftMin = leftMin->_left;
			}

			_node = leftMin;
		}
		else
		{
			Node* cur = _node;
			Node* parent = cur->_parent;
			while (parent && cur == parent->_right)
			{
				cur = parent;
				parent = parent->_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;

	RBTree(const RBTree<K, T, KeyOfT>&t)
	{
		_root = Copy(t._root);
	}

	// t2 = t1
	RBTree<K, T, KeyOfT>& operator=(RBTree<K, T, KeyOfT> t)
	{
		swap(_root, t._root);
		return *this;
	}

	~RBTree()
	{
		Destroy(_root);

		_root = nullptr;
	}

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

		return Iterator(leftMin);
	}

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

	ConstIterator Begin() const
	{
		Node* leftMin = _root;
		while (leftMin && leftMin->_left)
		{
			leftMin = leftMin->_left;
		}

		return ConstIterator(leftMin);
	}

	ConstIterator End() const
	{
		return ConstIterator(nullptr);
	}

	Iterator Find(const K& key)
	{
		KeyOfT kot;
		Node* cur = _root;

		while (cur)
		{
			if (kot(cur->_data) < key)
			{
				cur = cur->_right;
			}
			else if (kot(cur->_data) > 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;

		//kot对象,用来取T类型data中的key
		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(cur->_data))
		{
			parent->_right = cur;
		}
		else
		{
			parent->_left = cur;
		}
		cur->_parent = 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 = 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)
				{
					uncle->_col = parent->_col = BLACK;
					grandfather->_col = RED;

					cur = grandfather;
					parent = cur->_parent;
				}
				else//叔叔不存在,或者为黑
				{
					if (cur == parent->_right)
					{
						//			g
						//		u		p
						//					c
						
							RotateL(grandfather);
							grandfather->_col = RED;
							parent->_col = BLACK;
					}
					else
					{
							//			g
							//		u		p
							//			 c
							RotateR(parent);
							RotateL(grandfather);
							grandfather->_col = RED;
							cur->_col = BLACK;
					}
					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->_parent = parent;

		Node* ppNode = parent->_parent;

		SubL->_right = parent;
		parent->_parent = SubL;

		if (parent == _root)
		{
			_root = SubL;
			SubL->_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->_parent = parent;

		Node* ppNode = parent->_parent;

		SubR->_left = parent;
		parent->_parent = SubR;

		if (parent == _root)
		{
			_root = SubR;
			SubR->_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()
	{
		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)
		{
			if (blackNum != refNum)
			{
				cout << "存在黑色节点不相等的路线" << endl;
				return false;
			}
			return true;
		}

		if (root->_col == BLACK)
		{
			blackNum++;
		}

		if (root->_col == RED && root->_parent->_col == RED)
		{
			cout << "存在连续红色节点" << endl;
			return false;
		}

		return Check(root->_left, blackNum, refNum)
			&& Check(root->_right, blackNum, refNum);
	}

	
	void _InOrder(Node* root)
	{
		if (root == nullptr)
		{
			return;
		}

		_InOrder(root->_left);
		// 输出数据
		if constexpr (std::is_same<T, std::pair<K, typename std::remove_const<K>::type>>::value)
		{
			cout << root->_data.first << ":" << root->_data.second << endl;
		}
		else
		{
			cout << root->_data << endl;
		}
		_InOrder(root->_right);
	}

	
	Node* _root = nullptr;
};




set的代码

#pragma once

namespace qq
{
	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;

		const_iterator begin() const
		{
			return _t.Begin();
		}

		const_iterator end() const
		{
			return _t.End();
		}

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

		iterator end()
		{
			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);
		s.insert(15);
		s.insert(7);
		s.insert(1);
		s.insert(5);
		s.insert(7);

		PrintSet(s);

		set<int>::iterator it = s.begin();
		while (it != s.end())
		{
			//*it += 5;

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

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

		set<int> copy = s;
		for (auto e : copy)
		{
			cout << e << " ";
		}
		cout << endl;
		//cout << copy._t.IsBalance() << endl;
	}
}

map的代码

#pragma once

namespace qq
{
	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, const K, MapKeyOfT>::ConstIterator const_iterator;

		const_iterator begin() const
		{
			return _t.Begin();
		}

		const_iterator end() const
		{
			return _t.End();
		}

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

		iterator end()
		{
			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({ "aa",1 });
		m.insert({ "basd",2 });
		m.insert({ "asdac",4 });
		m.insert({ "dsd",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[] = { "asd","qwe","sdf","cvb" };
		map<string, int> countMap;
		for (auto& e : arr)
		{
			countMap[e]++;
		}

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

  • 12
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++ STL中,红黑树的实现被封装在`std::map`和`std::set`这两个容器类中。这两个容器类都是基于红黑树实现的,它们提供了高效的查找、插入和删除操作,保证了元素的有序性。 STL中的红黑树实现与你提供的C++代码略有不同。STL中的红黑树使用节点颜色(红色或黑色)和节点指针(parent、left、right)来表示树的结构,而你提供的代码使用了模板和节点对象来实现。 在STL中,红黑树的插入和删除操作已经被封装在`std::map`和`std::set`中,使用起来非常简单。你只需要包含相应的头文件`<map>`或`<set>`,并使用`std::map`或`std::set`类来定义变量,就可以直接使用红黑树的功能了。 以下是使用STL中红黑树的简单示例: ```cpp #include <map> int main() { std::map<int, std::string> myMap; // 插入元素 myMap.insert(std::make_pair(1, "one")); myMap = "two"; // 查找元素 auto it = myMap.find(1); if (it != myMap.end()) { std::cout << it->second << std::endl; // 输 "one" } // 删除元素 myMap.erase(2); return 0; } ``` 在上面的示例中,我们使用`std::map`来创建一个键-值对的红黑树。我们使用`insert`函数插入元素,使用`find`函数查找元素,使用`erase`函数删除元素。 总结一下,C++ STL中的红黑树实现被封装在`std::map`和`std::set`中,使用起来非常方便。你可以直接包含相应的头文件,并使用这些类来实现红黑树的功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值