STL算法---堆算法

来源:互联网 发布:矩阵扰动 编辑:程序博客网 时间:2024/04/30 10:30

堆算法

有4个函数(make_heap, push_heap, pop_heap, sort_heap)


1. make_heap

把指定范围内的元素生成一个堆。
重载版本使用自定义比较操作
函数原形
template<class RanIt> void make_heap(RanIt first, RanIt last);

template<class RanIt, class Pred> void make_heap(RanIt first, RanIt last, Pred pr);


2. push_heap

假设first到last-1是一个有效堆, 在last位置上加入元素, 然后调用push_heap重新生成堆. (在指向该函数前, 必须先把元素插入容器后.)
重载版本使用指定的比较操作
函数原形
template<class RanIt>void push_heap(RanIt first, RanIt last);

template<class RanIt, class Pred> void push_heap(RanIt first, RanIt last, Pred pr);


3. pop_heap

把[first, last)重新排序, 原来堆头的元素放在last的位置上, 除原来堆头元素之外的元素重新排序, 产生新堆头. 可使用容器的back来访问被"弹出"的元素或者使用pop_back进行真正的删除. 
重载版本使用自定义的比较操作
函数原形
template<class RanIt> void pop_heap(RanIt first, RanIt last);

template<class RanIt, class Pred> void pop_heap(RanIt first, RanIt last, Pred pr);


4. sort_heap

对指定范围内的序列重新排序, 它假设该序列是个有序堆。
重载版本使用自定义比较操作
函数原形
template<class RanIt> void sort_heap(RanIt first, RanIt last);

template<class RanIt, class Pred> void sort_heap(RanIt first, RanIt last, Pred pr);

<pre name="code" class="cpp">/////////////////////////////////////////////////////////////#include "stdafx.h"#include <algorithm>#include <numeric>#include <functional>#include <vector>#include <iostream>int _tmain(int argc, _TCHAR* argv[]){int myints[] = {10, 20, 30, 5, 15};std::vector<int> v(myints, myints + 5);// 10, 20, 30, 5, 15// 生成栈std::make_heap (v.begin(),v.end());// 30, 20, 10, 5, 15// 出栈std::pop_heap (v.begin(),v.end());// 20, 15, 10, 5, 30v.pop_back();// 20, 15, 10, 5// 入栈v.push_back(99);// 20, 15, 10, 5, 99std::push_heap (v.begin(),v.end());// 99, 20, 10, 5, 15// 入栈v.push_back(30);// 99, 20, 10, 5, 15, 30std::push_heap (v.begin(),v.end());// 99, 20, 30, 5, 15, 10std::sort_heap (v.begin(),v.end());// 5, 10, 15, 20, 30, 99return 0;}

// 这里的功能确保第一个元素值是最大的.
参考:
http://www.cplusplus.com/reference/algorithm/push_heap/

个人理解:
1. 可以使用这些函数定义一些数据结构, 例如优先队列, 栈等.
0 0