模拟实现 priority_queue C++

模拟 priority_queue


底层维护一个vector,通过向上调整算法,向下调整算法维护堆结构。

提供基本接口。

#include <vector>
#include <algorithm>
#include <cassert>

//默认为大堆
template<class T>
class Heap
{
public:

	Heap() {}
	Heap(const Heap<T>& hp) :
		v(hp.v) {}

	void push(const T& x)
	{
		v.push_back(x);
		adjustUp(v.size() - 1);
	}

	void pop()
	{
		std::swap(v[0], v[v.size() - 1]);
		adjustDown(v.size() - 1, 0);
		v.pop_back();
	}
	T top()
	{
		assert(!v.empty());
		return v[0];
	}

	bool empty()
	{
		return v.empty();
	}


	size_t size()
	{
		return v.size();
	}

private:
	void adjustDown(int n, int parent)
	{
		int child = parent * 2 + 1;
		while (child < n)
		{
			if (child + 1 < n && v[child] < v[child + 1])
				child++;

			if (v[child] > v[parent])
			{
				std::swap(v[child], v[parent]);
				parent = child;
				child = child * 2 + 1;
			}
			else
			{
				break;
			}

		}

	}
	void adjustUp(int child)
	{
		int parent = (child - 1) / 2;

		while (child > 0)
		{
			if (v[parent] < v[child])
			{
				std::swap(v[parent], v[child]);
				child = parent;
				parent = (parent - 1) / 2;
			}
			else
			{
				break;
			}
		}
	}

	std::vector<T> v;
};

猜你喜欢

转载自blog.csdn.net/juggte/article/details/121318280