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


最開始在項目文檔看到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() const
13     {
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) const
34     {
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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM