重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

C++实现堆

#include 
using namespace std;
#include 
#include 

//仿函数
template
struct Less
{
	bool operator()(const T& left, const T& right)
	{
		return left < right;
	}
};

template
struct Greater
{
	bool operator()(const T& left, const T& right)
	{
		return left > right;
	}
};

template>//默认为小堆
class Heap
{
public:
	Heap()
	{}

	Heap(const T* array, size_t size)
	{
		for (size_t i = 0; i < size; ++i)
		{
			_a.push_back(array[i]);
		}

		for (int i = (_a.size()-2)/2; i >= 0; --i)
		{
			_AdjustDown(i);
		}
	}

	void Push(const T& x)
	{
		_a.push_back(x);

		_AdjustUp(_a.size()-1);
	}

	void Pop()
	{
		assert(!_a.empty());

		swap(_a[0], _a[_a.size()-1]);
		_a.pop_back();
		_AdjustDown(0);
	}

	T& GetTop()
	{
		assert(!_a.empty());

		return _a[0];
	}

	bool Empty()
	{
		return _a.empty();
	}

	size_t Size()
	{
		return _a.size();
	}

	void Print()
	{
		for (size_t i = 0; i < _a.size(); ++i)
		{
			cout<<_a[i]<<" ";
		}
		
		cout< 0)
		{
			if (compare(_a[child], _a[parent]))
			{
				swap(_a[parent], _a[child]);

				child = parent;
				parent = (child-1)/2;
			}
			else
			{
				break;
			}
		}
	}

protected:
	vector _a;
};


void Test()
{
	int a[10] = {10, 11, 13, 12, 16, 18, 15, 17, 14, 19};
	Heap> hp1(a, sizeof(a)/sizeof(a[0]));
	hp1.Print();
	cout<<"size:"<

C++实现堆

10年积累的成都网站制作、网站设计经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先网站制作后付款的网站建设流程,更有加查免费网站建设让你可以放心的选择与我们合作。


标题名称:C++实现堆
文章转载:http://cqcxhl.com/article/jgjcoc.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP