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

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

相关推荐
大侠归来1 小时前
C 语言 | 在函数中操作数组
c语言·c++·算法
liangshanbo12151 小时前
JavaScript 面试题:Object.keys() 的返回顺序是无序的吗?
开发语言·javascript·ecmascript
朝朝辞暮i7 小时前
C++ 第 23 课:class —— 开始真正进入面向对象
开发语言·c++·算法
小师兄吃牛肉8 小时前
C语言篇:宏
c语言·开发语言
郑同学的笔记8 小时前
【c++随笔28】strcmp 和 memcmp对比
开发语言·c++
随意起个昵称9 小时前
【背包dp】输出方案路径
c++·动态规划
言乐69 小时前
Python根据无法识别搜索词找出可能输入内容模型
开发语言·python·django·virtualenv·pygame
weixin_307779139 小时前
有限产能智能排产与动态重排智能体:从需求解构到技术实现
开发语言·人工智能·算法·架构
kakakahahahaha9 小时前
Windows C盘临时文件清理:%temp%、Windows Temp、Prefetch、Windows.old与hiberfil.sys处理指南
c语言·开发语言·windows
朝朝辞暮i9 小时前
C++ 第 27 课:智能指针 shared_ptr
开发语言·c++·算法