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

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

相关推荐
BadBadBad__AK2 小时前
线段树维护区间 k 次方和
c++·数学·算法·stl
卷无止境14 小时前
Eigen 库如何借助 OpenMP 加速计算
c++·后端
卷无止境14 小时前
OpenMPI、MPICH 与 OpenMP:关系、核心概念与架构全解
c++·后端
郝学胜_神的一滴2 天前
CMake 30:循环语法全解|foreach_while双循环精讲、迭代技巧与实战避坑指南
c++·cmake
卷无止境4 天前
C++ 的Eigen 库全解析
c++
卷无止境4 天前
现代 C++特性大盘点:一门脱胎换骨的老语言
c++·后端
郝学胜_神的一滴4 天前
CMake 27:缓存变量的特性、语法、类型与实操全解
c++·cmake
博客18006 天前
酷宝的使用方法,超好用的免费界面库,C++、MFC可用
c++·mfc·界面库·库来帮·酷宝
郝学胜_神的一滴6 天前
CMake 026:属性体系精讲、四大作用域全解 & 实战代码落地
c++·cmake
众少成多积小致巨6 天前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++