priority_queue(优先队列)的简单构造与用法
生活随笔
收集整理的這篇文章主要介紹了
priority_queue(优先队列)的简单构造与用法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
??
priority_queue
priority_queue 優先隊列,其底層是用堆來實現的。在優先隊列中,隊首元素一定是當前隊列中優先級最高的那一個。
在優先隊列中,沒有 front() 函數與 back() 函數,而只能通過 top() 函數來訪問隊首元素(也可稱為堆頂元素),也就是優先級最高的元素。
一、基本數據類型的優先級設置
其中第二個參數( vector ),是來承載底層數據結構堆的容器,第三個參數( less ),則是一個比較類,less 表示數字大的優先級高,而 greater 表示數字小的優先級高。
如果想讓優先隊列總是把最小的元素放在隊首,只需進行如下的定義:
priority_queue<int,vector<int>,greater<int> >q;示例代碼:
void test1(){//默認情況下,數值大的在隊首位置(降序)priority_queue<int> q;for(int i = 0;i <= 10;i ++)q.push(i);while(!q.empty()){cout<<q.top()<<" ";q.pop();}cout<<endl;//greater<int>表示數值小的優先級越大priority_queue<int,vector<int>,greater<int> > Q;for(int i = 0;i <= 10;i ++)Q.push(i);while(!Q.empty()){cout<<Q.top()<<" ";Q.pop();}}二、結構體的優先級設置
1.方式一:重載運算符 ‘<’
可以在結構體內部重載 ‘<’,改變小于號的功能(例如把他重載為大于號)
struct student{int grade;string name;//重載運算符,grade 值高的優先級大friend operator < (student s1,student s2){return s1.grade < s2.grade;}};示例代碼:
void test2(){priority_queue<student> q;student s1,s2,s3;s1.grade = 90;s1.name = "Tom";s2.grade = 80;s2.name = "Jerry";s3.grade = 100;s3.name = "Kevin";q.push(s1);q.push(s2);q.push(s3);while(!q.empty()){cout<<q.top().name<<":"<<q.top().grade<<endl;q.pop();} }/*結果:Kevin:100Tom:90Jerry:80*/2.方式二:把重載的函數寫在結構體外面
將比較函數寫在結構體外面,作為參數傳給優先隊列。
struct fruit{string name;int price;};struct cmp{// "<" 表示 price 大的優先級高bool operator() (fruit f1,fruit f2){return f1.price < f2.price;}};示例代碼:
void test3(){priority_queue<fruit,vector<fruit>,cmp> q;fruit f1,f2,f3;f1.name = "apple";f1.price = 5;f2.name = "banana";f2.price = 6;f3.name = "pear";f3.price = 7;q.push(f1);q.push(f2);q.push(f3);while(!q.empty()){cout<<q.top().name<<":"<<q.top().price<<endl;q.pop();}}/*結果:pear:7banana:6apple:5*/??
原博客鏈接:https://blog.csdn.net/pzhu_cg_csdn/article/details/79166858
總結
以上是生活随笔為你收集整理的priority_queue(优先队列)的简单构造与用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2020年十强城市名单出炉,南方城市霸榜
- 下一篇: 建行大学生信用卡额度标准 学历高低影响下