stl 堆算法
学习前提:数据结构与算法中的堆
对make_heap(), pop_heap(), push_heap()的用法做个总结:
make_heap()生成堆,他有两个参数,也可以有三个参数,前两个参数是指向开始元素的迭代器和指向结束元素的下一个元素的迭代器。第三个参数是可选的,可以用伪函数less()和greater()来生成大顶堆和小顶堆,其中type为元素类型。如果只传入前两个参数,默认是生成大顶堆。
push_heap()是在堆的基础上进行数据的插入操作,参数与make_heap()相同,需要注意的是,只有make_heap()和push_heap()同为大顶堆或小顶堆,才能插入。
pop_heap()是在堆的基础上,弹出堆顶元素。这里需要注意的是,pop_heap()并没有删除元素,而是将堆顶元素和数组最后一个元素进行了替换,如果要删除这个元素,还需要对数组进行pop_back()操作。
若用make_heap(), pop_heap(), push_heap(),需要添加头文件 # include
用less ()和greater () 需要添加头文件 # include
实例代码
#include
#include
#include
#include
using namespace std;
void printarray(int a[],int len)
{
for (int i=0;i
cout< }
cout<
void printvector(vector
{
for (int i=0;i
cout<
cout<
int a[100];
vector
int main()
{
int n;
cin>>n;
for (int i=0;i
cin>>a[i];
v.push_back(a[i]);
}
make_heap(a,a+n);
printarray(a,n);
make_heap(v.begin(),v.end());
printvector(v);
int x;
cin>>x;
a[n]=x;
push_heap(a,a+n+1);
printarray(a,n+1);
v.push_back(x);
push_heap(v.begin(),v.end());
printvector(v);
}
/*
in
7
4 3 7 8 5 3 4
6
out
8 5 7 3 4 3 4
8 5 7 3 4 3 4
8 6 7 5 4 3 4 3
8 6 7 5 4 3 4 3
*/
实例二
#include
#include
#include
#include
using namespace std;
void printarray(int a[],int len)
{
for (int i=0;i
cout< }
cout<
void printvector(vector
{
for (int i=0;i
cout<
cout<
int a[100];
vector
int main()
{
int n;
cin>>n;
for (int i=0;i
cin>>a[i];
v.push_back(a[i]);
}
make_heap(a,a+n,greater
printarray(a,n);
make_heap(v.begin(),v.end(),less
printvector(v);
int x;
cin>>x;
a[n]=x;
push_heap(a,a+n+1);
printarray(a,n+1);
v.push_back(x);
push_heap(v.begin(),v.end());
printvector(v);
push_heap(a,a+n+1,greater
printarray(a,n+1);
push_heap(v.begin(),v.end(),greater
printvector(v);
}
/*
in
7
4 3 7 8 5 3 4
6
out
7
3 3 4 8 5 7 4
8 5 7 3 4 3 4
3 3 4 8 5 7 4 6
8 6 7 5 4 3 4 3
3 3 4 6 5 7 4 8
3 8 7 6 4 3 4 5
*/