STL 堆操作

STL里面的堆操作一般有:make_heap(), push_heap(), pop_heap(), is_heap(), sort_heap()

他们的头文件函数是#include <
algorithm>

make_heap()

函数原型:void make_heap(first_pointer,end_pointer,compare_function);

一个参数是数组或向量的头指针,

第二个向量是尾指针,

第三个参数是比较函数的名字。在缺省的时候,默认最大堆。

作用:把这一段的数组或向量做成一个堆的结构。范围是(first,last)

pop_heap()

函数原型:void pop_heap(first_pointer,end_pointer,compare_function);

作用:并不是真正的把最大元素从堆中弹出,而是重新排序堆。它把firstlast-1交换,然后重新做成一个堆。可以使用容器的back来访问被“弹出“的元素或者使用pop_back来真正的删除。重载版本使用自定义的比较操作。

http://kb.cnblogs.com/a/1612665/中讲解了是该函数是如何工作的!

个人看法:很多资料都是上面的说法,那么这个函数应该也就是STL给我们提供的删除结点的方法,它应该不限于只交换first和last-1,如果我们想修改某个值,我们可以先用first获得指针,假设为p,然后调用pop_heap(p,last-1);然后将最后一个元素pop_back();通过跳进函数进行调试,发现在很短的时间内就能完成堆排序,但在删除任意函数时,并不像http://kb.cnblogs.com/a/1612665/中那样的算法进行删除的,但速度也很快,如果要究其实质,我觉得就得看STL源码分析了吧!哈哈大笑,这个问题现在还没解决呢?还有为什么没有提供修改某一个元素的值,然后成堆的函数,还是堆不需要这些操作?疑问

push_heap() 

函数原型:void pushheap(first_pointer,end_pointer,compare_function);

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

sort_heap()void sort_heap(first_pointer,end_pointer,compare_function);

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

//Coded By 代码疯子
#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
using namespace std;

void print(int elem)
{
	cout << elem << ' ';
}

int main()
{
	vector<int> coll;
	int n;

	while(cin >> n && n)
	{
		coll.push_back(n);
	}

	make_heap(coll.begin(), coll.end());
	cout << "After make_heap()" << endl;
	//for_each(coll.begin(), coll.end(), print);
	copy(coll.begin(),coll.end(),ostream_iterator<int>(cout," "));
	cout << endl;

	cin >> n;
	coll.push_back(n);
	push_heap(coll.begin(), coll.end());

	cout << "After push_heap()" << endl;
	for_each(coll.begin(), coll.end(), print);
	cout << endl;

	pop_heap(coll.begin()+1, coll.end());
	cout << "After pop_heap()" << endl;
	for_each(coll.begin(), coll.end(), print);
	cout << endl;

	cout << "coll.back() : " << coll.back() << endl;
	coll.pop_back();

	sort_heap(coll.begin(), coll.end());
	cout << "After sort_heap()" << endl;
	for_each(coll.begin(), coll.end(), print);
	cout << endl;

	return 0;
}

参考目录:

http://www.cppblog.com/guogangj/archive/2009/10/29/99729.html

http://kb.cnblogs.com/a/1612665/

还有代码疯子的代码!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值