【STL】c++ priority_queue的使用方法

來源:互聯網
上載者:User

標籤:

最開始在項目文檔看到priority_queue這個模板時,還以為是自己定義的呢,後來查了一下,原來這是STL中存在的一種優先隊列。

1.最簡單的使用方法

 std::priority_queue<int> q;預設從大到小

#include <iostream>#include <queue>#include <vector>int main(){std::priority_queue<int> q;for(int i=0;i<10;i++)q.push(i);while(!q.empty()){std::cout<<q.top()<<std::endl;q.pop();}for(int i=9;i>=0;i--){q.push(i);}while(!q.empty()){std::cout<<q.top()<<std::endl;q.pop();}return 0;}

  

2.自訂的方法

需要對操作符自訂

 1 #include <iostream> 2 #include <string> 3 #include <vector> 4 #include <queue> 5 class MyResult 6 { 7 public: 8     MyResult(std::string word,int dist,int fre) 9         :m_word(word),m_dist(dist),m_frequece(fre)10     {11     }12     std::string  get_word() const13     {14         return m_word;15     }16     int get_dist()17     {18         return m_dist;19     }20     int get_fre()21     {22         return m_frequece;23     }24 25 private:26     std::string m_word;27     int m_dist;28     int m_frequece;29 };30 class MyCompare//定義比較方法,先比較dist,dist小的在前面,如果dist相等,再比較fre,fre大的在前面31 {32 public:33     bool operator()( MyResult left, MyResult right) const34     {35         if(left.get_dist()==right.get_dist()) return left.get_fre()<right.get_fre();36         return left.get_dist()>right.get_dist();37     }38 };39 int main()40 {41     std::priority_queue<MyResult,std::vector<MyResult>,MyCompare> m_result;42     MyResult r1("hello",3,100),r2("world",2,60),r3("jimmy",2,100),r4("kill",4,600);43     m_result.push(r1);44     m_result.push(r2);45     m_result.push(r3);46     m_result.push(r4);47     while(!m_result.empty())48     {49         std::cout<<m_result.top().get_word()<<std::endl;50         m_result.pop();51     }52     return 0;53 }

運行結果為:

jimmy

world

hello

kill

【STL】c++ priority_queue的使用方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.