码迷,mamicode.com
首页 > 其他好文 > 详细

STL中堆的应用

时间:2015-05-12 18:47:27      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:

#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;
}

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

STL中堆的应用

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!