1. 程式人生 > 程式設計 >c++優先佇列(priority_queue)用法詳解

c++優先佇列(priority_queue)用法詳解

普通的佇列是一種先進先出的資料結構,元素在佇列尾追加,而從佇列頭刪除。

在優先佇列中,元素被賦予優先順序。當訪問元素時,具有最高優先順序的元素最先刪除。優先佇列具有最高階先出 (first in,largest out)的行為特徵。

首先要包含標頭檔案#include<queue>,他和queue不同的就在於我們可以自定義其中資料的優先順序,讓優先順序高的排在佇列前面,優先出隊。

優先佇列具有佇列的所有特性,包括佇列的基本操作,只是在這基礎上添加了內部的一個排序,它本質是一個堆實現的。

和佇列基本操作相同:

  • top 訪問隊頭元素
  • empty 佇列是否為空
  • size 返回佇列內元素個數
  • push 插入元素到隊尾 (並排序)
  • emplace 原地構造一個元素並插入佇列
  • pop 彈出隊頭元素
  • swap 交換內容

定義:priority_queue<Type,Container,Functional>
Type 就是資料型別,Container 就是容器型別(Container必須是用陣列實現的容器,比如vector,deque等等,但不能用 list。STL裡面預設用的是vector),Functional 就是比較的方式。

當需要用自定義的資料型別時才需要傳入這三個引數,使用基本資料型別時,只需要傳入資料型別,預設是大頂堆。
一般是:

//升序佇列
priority_queue <int,vector<int>,greater<int> > q;
//降序佇列
priority_queue <int,less<int> >q;

//greater和less是std實現的兩個仿函式(就是使一個類的使用看上去像一個函式。其實現就是類中實現一個operator(),這個類就有了類似函式的行為,就是一個仿函式類了)

1、基本型別優先佇列的例子:

#include<iostream>
#include <queue>
using namespace std;
int main() 
{
  //對於基礎型別 預設是大頂堆
  priority_queue<int> a; 
  //等同於 priority_queue<int,less<int> > a;
  
  //   這裡一定要有空格,不然成了右移運算子↓↓
  priority_queue<int,greater<int> > c; //這樣就是小頂堆
  priority_queue<string> b;

  for (int i = 0; i < 5; i++) 
  {
    a.push(i);
    c.push(i);
  }
  while (!a.empty()) 
  {
    cout << a.top() << ' ';
    a.pop();
  } 
  cout << endl;

  while (!c.empty()) 
  {
    cout << c.top() << ' ';
    c.pop();
  }
  cout << endl;

  b.push("abc");
  b.push("abcd");
  b.push("cbd");
  while (!b.empty()) 
  {
    cout << b.top() << ' ';
    b.pop();
  } 
  cout << endl;
  return 0;
}

執行結果:

4 3 2 1 0
0 1 2 3 4
cbd abcd abc
請按任意鍵繼續. . .

2、用pair做優先佇列元素的例子:

規則:pair的比較,先比較第一個元素,第一個相等比較第二個。

#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int main() 
{
  priority_queue<pair<int,int> > a;
  pair<int,int> b(1,2);
  pair<int,int> c(1,3);
  pair<int,int> d(2,5);
  a.push(d);
  a.push(c);
  a.push(b);
  while (!a.empty()) 
  {
    cout << a.top().first << ' ' << a.top().second << '\n';
    a.pop();
  }
}

執行結果:

2 5
1 3
1 2
請按任意鍵繼續. . .

3、用自定義型別做優先佇列元素的例子

#include <iostream>
#include <queue>
using namespace std;

//方法1
struct tmp1 //運算子過載<
{
  int x;
  tmp1(int a) {x = a;}
  bool operator<(const tmp1& a) const
  {
    return x < a.x; //大頂堆
  }
};

//方法2
struct tmp2 //重寫仿函式
{
  bool operator() (tmp1 a,tmp1 b) 
  {
    return a.x < b.x; //大頂堆
  }
};

int main() 
{
  tmp1 a(1);
  tmp1 b(2);
  tmp1 c(3);
  priority_queue<tmp1> d;
  d.push(b);
  d.push(c);
  d.push(a);
  while (!d.empty()) 
  {
    cout << d.top().x << '\n';
    d.pop();
  }
  cout << endl;

  priority_queue<tmp1,vector<tmp1>,tmp2> f;
  f.push(b);
  f.push(c);
  f.push(a);
  while (!f.empty()) 
  {
    cout << f.top().x << '\n';
    f.pop();
  }
}

執行結果:

3
2
1

3
2
1
請按任意鍵繼續. . .

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。