STL中堆的应用

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<vector>
#include<cmath>
using namespace std;
int a[100];
bool cmp(int a,int b)
{
     return a>b;
}
int main()
{
//-------------------------------------------------
//建堆,make_heap(&first,&last) 范围:[first,last)。 
    for (int i=0;i<=11;i++) scanf("%d",&a[i]);
    make_heap(&a[0],&a[12]); //大根堆 
    for (int i=0;i<=11;i++) printf("%d ",a[i]); cout<<endl;
    make_heap(&a[0],&a[12],cmp); //小根堆 
    for (int i=0;i<=11;i++) printf("%d ",a[i]); cout<<endl;
//-------------------------------------------------
//向堆中压入元素 push_heap(&first,&last),并调整堆。 范围:[first,last-1]。 
    a[12]=22; 
    push_heap(&a[0],&a[13],cmp); //小根堆。 
    for (int i=0;i<=12;i++) printf("%d ",a[i]); cout<<endl;
//-------------------------------------------------
//弹出堆顶的元素(将其置于数组的末尾,堆的范围右边界-1) pop_heap(&first,&last) 
//范围:[first,last-1]。 
    pop_heap(&a[0],&a[13],cmp);
    for (int i=0;i<=12;i++) printf("%d ",a[i]); cout<<endl; 
//-------------------------------------------------
//堆排序 sort_heap(&first,&last,cmp) 范围:[first,last)。 
    sort_heap(&a[0],&a[12],cmp);
    for (int i=0;i<=11;i++) printf("%d ",a[i]); cout<<endl; 
//-------------------------------------------------
    system("pause");
    return 0;
}

在网上看了很多,有的太乱,有的不实用,自己总结了一下。

原文地址:https://www.cnblogs.com/ws-fqk/p/4498138.html