STL Heap

白昼怎懂夜的黑 提交于 2020-01-21 15:49:36

概述

♦STL 并没有把heap作为一种容器组件,它是实现优先队列的助手。它的实现是依靠vector表现的完全二叉树。
♦STL中默认是最大堆,但是用户利用自定义的compare_fuction函数实现最小堆。
♦heap是一个类属算法,在头文件#include< algorithm>中声明。

常见函数

make_heap

pop_heap

push_heap

sort_heap

测试代码

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
	int n;
	cin >> n;
	vector<int>v;
	for (int i = 0; i < n; i++)
	{
		int num;
		cin >> num;
		v.push_back(num);
	}
	make_heap(v.begin(), v.end());
	cout << "init max heap:" << v.front() << endl;
	pop_heap(v.begin(), v.end());
	v.pop_back();
	cout << "max heap after pop:" << v.front() << endl;
	v.push_back(999);
	push_heap(v.begin(), v.end());
	cout << "max heap after push:" << v.front() << endl;
	sort_heap(v.begin(), v.end());
	cout << "final sorted range:";
	for (int i = 0; i < v.size(); i++)
	{
		cout << v[i] << " ";
	}
	cout << endl;
	return 0; 
}

测试结果

在这里插入图片描述

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!