C++之priority_queue实现

闲话少说,代码起步!!!

cpp 复制代码
#pragma once


namespace cx
{
	template<class T,class container=vector<T>, class Compare = less<T>>
	class priority_queue
	{
	public:
		void adjust_up(int child)
		{
			Compare com;
			int parent = (child - 1) / 2;
			while (child > 0)
			{
				if(com( _con[child], _con[parent]))
				{
					swap(_con[child], _con[parent]);
					child = parent;
					parent = (child - 1) / 2;
				}
				else
				{
					break;
				}
			}
		}
		void adjust_down(int parent)
		{
			int child = parent * 2 + 1;
			Compare com;
			while (child< _con.size())
			{
				if (child + 1 < _con.size()&& com(_con[child + 1],_con[child]))
					child++;
				if (com(_con[child], _con[parent]))
				{
					swap(_con[parent], _con[child]);
					parent = child;
					child = parent * 2 + 1;
				}
				else
				{
					break;
				}
			}
		}
		void push(const T& x)
		{
			_con.push_back(x);
			adjust_up((int)size() - 1);
		}
		void pop()
		{
			swap(_con[0], _con[size() - 1]);
			_con.pop_back();
			adjust_down(0);
		}
		bool empty()
		{
			return _con.empty();
		}
		size_t size()const
		{
			return _con.size();
		}
		const T& top()
		{
			return _con[0];
		}
		void swap(T& a,T& b)
		{
			std::swap(a, b);
		}
	private:
		container _con;
	};
	template<class T>
	class greater
	{
	public:
		bool operator()(const T& a, const T& b)
		{
			return a < b;
		}
	};
	template<class T>
	class less
	{
	public:
		bool operator()(const T& a, const T& b)
		{
			return a > b;
		}
	};
}

希望大家可以参考可以实现自己的代码,感谢大家的阅读。

相关推荐
点云SLAM1 小时前
二叉树算法详解和C++代码示例
数据结构·c++·算法·红黑树·二叉树算法
Sylvia-girl4 小时前
Java——抽象类
java·开发语言
Yana.nice6 小时前
Bash函数详解
开发语言·chrome·bash
m0_535064607 小时前
C++模版编程:类模版与继承
java·jvm·c++
tomorrow.hello8 小时前
Java并发测试工具
java·开发语言·测试工具
晓13139 小时前
JavaScript加强篇——第四章 日期对象与DOM节点(基础)
开发语言·前端·javascript
老胖闲聊9 小时前
Python I/O 库【输入输出】全面详解
开发语言·python
Tanecious.9 小时前
C++--红黑树封装实现set和map
网络·c++
她说人狗殊途10 小时前
java.net.InetAddress
java·开发语言
天使day10 小时前
Cursor的使用
java·开发语言·ai