STL--priority_queue--自定義數據類型


STL中priority_queue的聲明模板有3個參數priority_queue<Type,Container,Functional>。

當使用的數據類型Type為自定義數據類型時有以下3種方法。

1)寫仿函數

 1 #include<iostream>
 2 #include<queue>
 3 using namespace std;
 4 struct Node
 5 {
 6     int x,y;
 7 };
 8 struct cmp
 9 {
10     bool operator()(Node a,Node b)
11     {
12         if(a.x!=b.x)
13             return a.x<b.x;//<為大頂堆,>為小頂堆
14         return a.y<b.y;
15     }
16 };
17 int main()
18 {
19     Node node[9]={{0,0},{0,1},{0,2},{1,0},{1,1},{1,2},{2,0},{2,1},{2,2}};
20     //建立9個結點
21     priority_queue <Node,vector<Node>,cmp> q(node,node+9);//將9個點存入優先隊列q
22     while(!q.empty())//輸出
23     {
24         Node n=q.top();
25         cout<<n.x<<' '<<n.y<<endl;
26         q.pop();
27     }
28     return 0;
29 }

2)數據類型外重載operator<

 1 #include<iostream>
 2 #include<queue>
 3 using namespace std;
 4 struct Node
 5 {
 6     int x,y;
 7 };
 8 bool operator<(Node a,Node b)
 9 {
10     if(a.x!=b.x)
11         return a.x<b.x;//<為大頂堆,>為小頂堆
12     return a.y<b.y;
13 }
14 int main()
15 {
16     Node node[9]={{0,0},{0,1},{0,2},{1,0},{1,1},{1,2},{2,0},{2,1},{2,2}};
17     //建立9個結點
18     priority_queue <Node> q(node,node+9);//將9個點存入優先隊列q
19     while(!q.empty())//輸出
20     {
21         Node n=q.top();
22         cout<<n.x<<' '<<n.y<<endl;
23         q.pop();
24     }
25     return 0;
26 }

3)數據類型內重載operator<

 1 #include<iostream>
 2 #include<queue>
 3 using namespace std;
 4 struct Node
 5 {
 6     int x,y;
 7     bool operator<(const Node a)const
 8     {
 9         if(x!=a.x)
10             return x<a.x;
11         return y<a.y;
12     }
13 };
14 int main()
15 {
16     Node node[9]={{0,0},{0,1},{0,2},{1,0},{1,1},{1,2},{2,0},{2,1},{2,2}};
17     //建立9個結點
18     priority_queue <Node> q(node,node+9);//將9個點存入優先隊列q
19     while(!q.empty())//輸出
20     {
21         Node n=q.top();
22         cout<<n.x<<' '<<n.y<<endl;
23         q.pop();
24     }
25     return 0;
26 }

 


免責聲明!

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



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