堆函数

一般解题过程中,我们都是手写堆和与堆相关的操作,其实STL里面已经定义了相关函数

STL中封装了有关堆操作的函数头文件:<algorithm>

STL里面的堆操作一般用到的只有4个:make_heap();、pop_heap();、push_heap();、sort_heap();

一、make_heap();

  1. 他的函数原型是:void make_heap(first_pointer,end_pointer,compare_function);
  2. 一个参数是数组或向量的头指针,第二个向量是尾指针。第三个参数是比较函数的名字。在缺省的时候,默认是大跟堆。(下面的参数都一样就不解释了)
  3. 作用:把这一段的数组或向量做成一个堆的结构。范围是(first,last)

二、pop_heap();

  1. 它的函数原型是:void pop_heap(first_pointer,end_pointer,compare_function);
  2. 作用:pop_heap()不是真的把最大(最小)的元素从堆中弹出来。而是重新排序堆。它把first和last交换,然后将[first,last-1)的数据再做成一个堆。

三、push_heap()

  1. void push_heap(first_pointer,end_pointer,compare_function);
  2. 作用:push_heap()假设由[first,last-1)是一个有效的堆,然后,再把堆中的新元素加进来,做成一个堆。

四、sort_heap()

  1. void sort_heap(first_pointer,end_pointer,compare_function);
  2. 作用是sort_heap对[first,last)中的序列进行排序。它假设这个序列是有效堆。(当然,经过排序之后就不是一个有效堆了)

代码:

#include<algorithm>
#include<cstdio>
using namespace std;
int number[20]={29,23,20,22,17,15,26,51,19,12,35,40};
bool cmp(int a,int b)//调整小根堆要用到 
{
	return a>b;
}
void print(int n)
{
	for(int i=0;i<n;i++) 
	printf("%d ",number[i]); 
	printf("\n");
} 
int main()
{
	make_heap(&number[0],&number[12]);	print(12);
	//结果 :51 35 40 23 29 20 26 22 19 12 17 15
			
	make_heap(&number[0],&number[12],cmp); 	print(12);
	//结果:12 17 15 19 23 20 26 51 22 29 35 40
			
	//加入元素8		//加入后调整
	number[12]=8;
	push_heap(&number[0],&number[13],cmp);	print(13);
	//结果:8 17 12 19 23 15 26 51 22 35 40 20	
	
	//弹出堆顶元素8	
	pop_heap(&number[0],&number[13],cmp);	print(12);	
	//结果:12 17 15 19 23 20 26 51 22 29 35 40	
	
	//结果不用说都知道是有序的了!	
	sort_heap(&number[0],&number[12],cmp);	print(12);	
	
	return 0;	
}

参考自:https://blog.csdn.net/CillyB/article/details/52224330

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值