概述
♦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;
}