STL笔记:heap and priority sort

来源:互联网 发布:js window.open返回值 编辑:程序博客网 时间:2024/06/05 20:11

1. heap

heap的相关实现需要include “algorithm”, heap分为max heap和min heap,默认为max, 这也是heapsort和priority queue的底层实现机制。基本实现实际上是基于vector的完全二叉树。常见操作包括:make_heap, pop_heap, push_heap, sort_heap。算法题目中熟悉这些STL操作十分重要。

1.make_heap():

make_heap(_First, _Last)

make_heap(_First, _Last, _Comp)

默认是建立最大堆的。对int类型,可以在第三个参数传入greater< int >()得到最小堆。

2.push_heap(_First, _Last):

新添加一个元素在末尾,然后重新调整堆序。也就是把元素添加在底层vector的end()处。

该算法必须是在一个已经满足堆序的条件下,添加元素。该函数接受两个随机迭代器,分别表示first,end,区间范围。

关键是我们执行一个siftup()函数,在之前的博客里用伪代码表示过,就是在已有的堆基础上,不断地跟parent(i)比较来重新定位新添加的元素,所以用上溯函数来重新调整堆序。

3.pop_heap(_First, _Last):

这个算法跟push_heap类似,参数一样。不同的是我们把堆顶元素取出来,放到了数组或者是vector的末尾,用原来末尾元素去替代,然后end迭代器减1,执行siftdown()下溯函数来重新调整堆序,相当于之前伪代码的heapify。

注意算法执行完毕后,最大的元素并没有被取走,而是放于底层容器的末尾。如果要取走,则可以使用底部容器(vector)提供的pop_back()函数。

4.sort_heap(_First, _Last):

既然每次pop_heap可以获得堆中最大的元素,那么我们持续对整个heap做pop_heap操作,每次将操作的范围向前缩减一个元素。当整个程序执行完毕后,我们得到一个非降的序列。注意这个排序执行的前提是,在一个堆上执行。

下面是这几个函数操作vector中元素的例子。

#include<iostream>  #include<vector>  #include<algorithm>  using namespace std;  int main()  {      int a[] = {15, 1, 12, 30, 20};      vector<int> ivec(a, a+5);      for(vector<int>::iterator iter=ivec.begin();iter!=ivec.end();++iter)          cout<<*iter<<" ";      cout<<endl;      make_heap(ivec.begin(), ivec.end());//建堆      for(vector<int>::iterator iter=ivec.begin();iter!=ivec.end();++iter)          cout<<*iter<<" ";      cout<<endl;      pop_heap(ivec.begin(), ivec.end());//先pop,然后在容器中删除      ivec.pop_back();      for(vector<int>::iterator iter=ivec.begin();iter!=ivec.end();++iter)          cout<<*iter<<" ";      cout<<endl;      ivec.push_back(99);//先在容器中加入,再push      push_heap(ivec.begin(), ivec.end());      for(vector<int>::iterator iter=ivec.begin();iter!=ivec.end();++iter)          cout<<*iter<<" ";      cout<<endl;      sort_heap(ivec.begin(), ivec.end());      for(vector<int>::iterator iter=ivec.begin();iter!=ivec.end();++iter)          cout<<*iter<<" ";      cout<<endl;      return 0;  }  

输出结果如下:
输出结果

2. priority queue

优先队列, priority queue首先是一个queue,所以在末端推入,顶端取出。内部按照优先级高低排序,缺省的情况下依靠max heap 实现, 它跟heap一样,也不是STL的基础容器,是基于容器实现的特殊结构,我们称之为,适配器,adapter。

主要函数包括:
bool empty() const
size_type size() const
const_reference top() const
返回顶端元素。不取走。
void push(const value_type& x)
内部调用push_back(x)和push_heap()
void pop()
内部调用pop_heap()和pop_back();

在优先队列中,优先级高的元素先出队列。
标准库默认使用元素类型的<操作符来确定它们之间的优先级关系。
优先队列的第一种用法,也是最常用的用法:

priority_queue< int > qi;
所以此时就是元素整数值大的优先级高,先输出。

第二种方法:
在示例1中,如果我们要把元素从小到大输出怎么办呢?
这时我们可以传入一个比较函数,使用functional.h函数对象作为比较函数。

priority_queue< int, vector< int >, greater< int > >qi2;

其中
第二个参数为容器类型。
第三个参数为比较函数。greater对应min heap, less对应max heap;

第三种方法:
自对自定义的数据类型自定义优先级,
1.通过自定义operator<操作符来比较元素中的优先级。

struct Node{       int key;       int valuebool operator <(const Node & a,const Node & b)       {              return a.key<b.key;       }       bool operator > (const Node & a,const Node & b)       {               return a.key>b.key;       }};

在该结构中,value为值,key为优先级,使用示例:
priority_queue< Node,vector< Node >,less< Node > > pqLess;
priority_queue< Node,vector< Node >,greater< Node > > pqGreater;

2.自定义一个比较“类”,重载括号,operator (),这这种方式可以由less“继承”

struct Node{        int key;        int value;};struct cmpLess{         bool operator ()(const Node & a,const Node & b)         {              return a.key<b.key;         }};struct cmpGreater{          bool operator ()(const Node & a,const Node & b)          {               return a.key>b.key;          }};

使用示例:
priority_queue< Node,vector< Node >,cmpLess> pqLess;
priority_queue< Node,vector< Node >,cmpGreater> pqGreater;

具体实现代码举例如下:

#include "stdafx.h"#include <vector>#include <queue>#include <functional>using namespace std;struct node{    int key;    int value;};bool operator < (const node& a, const node& b) {    return a.key < b.key;}bool operator > (const node& a, const node& b) {    return a.key > b.key;}int main {    const int len = 5;    int i;    int a[len] = { 3,5,9,6,2 };    priority_queue<int> qi;    for (i = 0; i < len; i++)        qi.push(a[i]);    for (i = 0; i < len; i++) {        cout << qi.top() << " ";        qi.pop();    }    cout << endl;    priority_queue<node, vector<node>, less<node> > pq2;    //priority_queue<Node,vector<Node>,cmpLess> pq2;      vector<node> b(len);    b[0].key = 6; b[0].value = 1;    b[1].key = 9; b[1].value = 5;    b[2].key = 2; b[2].value = 3;    b[3].key = 8; b[3].value = 2;    b[4].key = 1; b[4].value = 4;    for (i = 0; i < len; i++)        pq2.push(b[i]);    cout << "优先级" << '\t' << "值" << endl;    for (i = 0; i < len; i++) {        cout << pq2.top().key << '\t' << pq2.top().value << endl;        pq2.pop();    }    return 0;}

运行输出如下:
priority output

1 0