您的位置:首页 > 编程语言 > C语言/C++

(转)【C++ STL】细数C++ STL 的那些事 -- priority_queue(优先队列)

2013-11-21 16:34 585 查看
装载自/article/1413075.html

一,概述

priority_queue是拥有权值观念的queue,它允许加入新元素,移除旧元素。调用 STL里面的 make_heap(), pop_heap(), push_heap() 算法实现,也算是堆的另外一种形式。但它是一个queue所以只允许在底端加入元素,在顶端移除元素。

排序:按照权值大小顺序排序,而不是按照push 进去的顺序排序。权值高者排在前面,权值低者排在后面。

允许以任何大小顺序插入到优先队列,但取出时是按照权值大小取。

二,heap(堆)简介

1)采用vector存储,是一颗完全二叉树(complete binary tree)的形式。

heap分为 max_heap 和 min_heap,前者最大权值在根,后者最小权值在根。

2)建立堆过程

vector中元素先调整为堆的形式。

插入元素时,将元素放到vector 的最后面end(),然后上溯调整堆。

3)heap算法 // #include <algorithm>

make_heap(first,last) //初建堆

push_heap(first,last) //插入元素,并调整为堆

pop_heap(first,last) //弹出元素,并调整为堆

sort_heap(first,last) //堆排序

4)示例

#include <iostream>
#include <queue>

using namespace std;

struct Node{
int x, y;
Node( int a= 0, int b= 0 ):
x(a), y(b) {}
};

struct cmp{
bool operator() ( Node a, Node b ){
if( a.x== b.x ) return a.y> b.y;

return a.x> b.x; }
};

int main(){
priority_queue<Node, vector<Node>, cmp> q;

for( int i= 0; i< 10; ++i )
q.push( Node( rand(), rand() ) );

while( !q.empty() ){
cout << q.top().x << ' ' << q.top().y << endl;
q.pop();
}

getchar();
return 0;
}


View Code
要注意的是,如果重载cmp,return a > b的形式形成的堆堆顶为最小元素!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: