【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