STL:priority_queue和heap笔记

版权声明:所有文章版权归属博主个人 https://blog.csdn.net/weixin_41143631/article/details/88670939

heap数据结构,图和原理网上很多。

我的一个堆排序,这是堆思想的一个应用。

	void adjustHeap(int a[], int i, int size)
	{
		//int max;
		int l = 2 * i + 1;
		int r = 2 * i + 2;
		int max = i;
		//vs 2017 会检测&&右边的,故不能将l < size&& a[l] > a[max]书写
		if (l < size) {
			if ( a[l] > a[max])
				max = l;
		}
		if (r < size) {
			if ( a[r] > a[max])
				max = r;
		}
		if (max != i)
		{
			swap(a[i], a[max]);
			adjustHeap(a, max, size);
		}
	}
	void heapSort(int a[],int size)
	{
		for (int i = size / 2 - 1; i >=0; i--)
		{
			adjustHeap(a, i, size);
		}
		for (int i = size-1;i >= 0; i--)
		{
			swap(a[0], a[i]);
			adjustHeap(a, 0, i);
		}
	}

系统中优先级队列也是按照heap的思想实现的,heap只考虑top(),故无迭代器。我用priority_queue实现上面同样的功能。


void testPriorityQueue()
{
	//优先级队列默认是大堆
	int array[] = { 1,3,54,6,57,45,345,4 };
	int size = sizeof(array) / sizeof(array[0]);
	priority_queue<int> pq;
	for (auto e : array)
	{
		pq.push(e);
	}
	for (int i=0; i < size; i++)
	{
		cout << pq.top()<<">";
		pq.pop();
	}

	// 如果要创建小堆,将第三个模板参数换成greater比较方式
	vector<int> v = { 1,3,54,6,57,45,345,4 };
	priority_queue<int, vector<int>, greater<int>> q2(v.begin(), v.end());
}

也很方便,当我们只关心top问题时,heap和priority_queue便派上用场了。 

猜你喜欢

转载自blog.csdn.net/weixin_41143631/article/details/88670939