STL中堆和優先隊列的使用方法

一、heap
#include<algorithm>
make_heap(首位置, 尾位置+1, 可選的cmp函數); 
-> 構造堆,將數組堆化
push_heap(首位置, 尾位置+1, 可選的cmp函數); 
-> 添加元素到底層容器末尾,並將堆的作用範圍擴展到這個元素,最後調整堆序 
pop_heap(首位置, 尾位置+1, 可選的cmp函數);  
-> 將堆頂元素與堆尾元素交換,並將堆的作用範圍向小的方向縮小一個,最後調整堆序 
sort_heap(首位置, 尾位置+1, 可選的cmp函數); 
-> 整個堆進行排序
push_heap(heap.begin(),heap.end(),less<int>());
push_heap(heap.begin(),heap.end());
按大頂堆調整堆序
push_heap(heap.begin(),heap.end(),greater<int>());
按小頂堆調整堆序

二、priority_queue
#include<queue>

q.empty()             如果隊列爲空,則返回true,否則返回false

q.size()                返回隊列中元素的個數

q.pop()             刪除隊首元素,但不返回其值

q.top()            返回具有最高優先級的元素值,但不刪除該元素

q.push(item)            在基於優先級的適當位置插入新元素

priority_queue<int> que;
採用默認優先級構造隊列
priority_queue<int,vector<int>,cmp> que;
按自定義優先級構造隊列
priority_queue<int,vector<int>,greater<int> > que;
最小值優先
priority_queue<int,vector<int>,less<int> > que;
最大值優先

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章