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

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

相关推荐
肆忆_4 小时前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星8 小时前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛2 天前
delete又未完全delete
c++
端平入洛3 天前
auto有时不auto
c++
郑州光合科技余经理4 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1234 天前
matlab画图工具
开发语言·matlab
dustcell.4 天前
haproxy七层代理
java·开发语言·前端
norlan_jame4 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20214 天前
信号量和信号
linux·c++
多恩Stone4 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc