(轉)C++STL中優先隊列的使用

來源:互聯網
上載者:User

標籤:style   name   const   namespace   sdn   article   複雜   bool   str   

原文地址

說到隊列,我們首先想到就是先進先出,後進後出;那麼何為優先隊列呢,在優先隊列中,元素被賦予優先順序,當訪問元素時,具有最進階優先順序的元素先被訪問。即優先隊列具有最進階先出的行為特徵。

優先隊列在標頭檔#include <queue>中;

其聲明格式為:priority_queue <int> ans;//聲明一個名為ans的整形的優先隊列

基本操作有:

empty( )  //判斷一個隊列是否為空白

pop( )  //刪除隊頂元素

push( )  //加入一個元素

size( )  //返回優先隊列中擁有的元素個數

top( )  //返回優先隊列的隊頂元素

優先隊列的時間複雜度為O(logn),n為隊列中元素的個數,其存取都需要時間。

在預設的優先隊列中,優先順序最高的先出隊。預設的int類型的優先隊列中先出隊的為隊列中較大的數。

然而更多的情況下,我們是希望可以自訂其優先順序的,下面介紹幾種常用的定義優先順序的操作:

#include <iostream>  #include <vector>  #include <queue>  using namespace std;  int tmp[100];  struct cmp1  {       bool operator ()(int x, int y)      {          return x > y;//小的優先順序高      }  };  struct cmp2  {      bool operator ()(const int x, const int y)      {          return tmp[x] > tmp[y];           //tmp[]小的優先順序高,由於可以在隊外改變隊內的值,          //所以使用此方法達不到真正的優先,建議用結構體類型。      }  };  struct node  {      int x, y;      friend bool operator < (node a, node b)      {          return a.x > b.x;//結構體中,x小的優先順序高      }  };    priority_queue<int>q1;  priority_queue<int, vector<int>, cmp1>q2;  priority_queue<int, vector<int>, cmp2>q3;  priority_queue<node>q4;  int main()  {      int i,j,k,m,n;      int x,y;      node a;      while(cin>>n)      {          for(int i=0;i<n;i++)          {              cin>>a.y>>a.x;              q4.push(a);          }          cout << endl;          while(!q4.empty())          {              cout<<q4.top().y <<" "<<q4.top().x<<endl;              q4.pop();          }          cout << endl;      }      return 0;  }  

 

(轉)C++STL中優先隊列的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.