优先队列
c++ STL 中 优先队列用法(默认为less,最大堆),头文件为需要包括 :
#include <queue> /* * std::priority_queue: * template <class T, class Container = vector<T>, * class Compare = less<typename Container::value_type> > class * priority_queue; */
例子:
int a[7] = {1,4,5,2,8,3,0}; priority_queue <int, vector<int>, less<int> > p; priority_queue <int, vector<int>, greater<int> >q; for(int i = 0; i < 5; i++) { p.push(a[i]); q.push(a[i]); } //output p:8 5 4 2 1 //output q:1 2 4 5 8
2. greater的用法:
// greater example #include <iostream> // std::cout #include <functional> // std::greater #include <algorithm> // std::sort int main () { int numbers[]={20,40,50,10,30}; std::sort (numbers, numbers+5, std::greater<int>()); for (int i=0; i<5; i++) std::cout << numbers[i] << ' '; std::cout << ' '; return 0; } /************output: 50 40 30 20 10 *************/
3. 在优先队列中使用greater: 却是从小到大排列顺序。
#include <queue> #include <iostream> #include <vector> #include <algorithm> using namespace std; class cmp { bool reverse; public: cmp(const bool &re = false) { reverse = re; } bool operator() (int &a, int &b) const { if(reverse) return (a > b); else return (a < b); } }; int main() { int myints[] = {10, 60, 50, 20}; //默认从大到小 默认为less priority_queue<int> second (myints, myints+4); //60, 50, 20, 10 while(!second.empty()) { cout << " " << second.top(); second.pop(); } cout << endl; /*从小到大: 10, 20, 50, 60*/ priority_queue<int, vector<int>, greater<int> > third (myints, myints + 4); while(!third.empty()) { cout << " " << third.top(); third.pop(); } cout << endl; /*从小到大, 10 ,20, 50, 60*/ priority_queue<int, vector<int>, cmp> fourth(myints, myints+4, cmp(true)); while(!fourth.empty()) { cout << " " << fourth.top(); fourth.pop(); } cout << endl; return 0; }