From the Internet search priority queue usage, are a bit of a mess, there are several uses have not said, directly paste code. Really depressed, so I summed up in this.
Nonsense not much to say, straight into the subject.
The core of the priority queue is the implementation of the comparison function.
There are two ways to implement a comparison function:
1. Define a comparison structure outside the struct or class. If there is a point struct. The new object is:priority_queue<point,vector<point>,cmp> PG; Where CMP is a custom comparison function
2. Overload < operator in struct or class. If there is a point struct. This approach defines the priority queue: Priority_queue<point> PG;
The 1th method implements the code:
#include <iostream> #include <queue> #include <algorithm> #include <vector>using namespace std; Class Point{public: int x, y;}; struct cmp{ bool operator () (point A,point B) { return a.x>b.x; Return!cmp }};p riority_queue<point,vector<point>,cmp> PQ; Point P;int Main () { int n; while (Cin>>n) { while (!pq.empty ()) Pq.pop (); while (n--) { cin>>p.x>>p.y; Pq.push (P); } while (!pq.empty ()) { cout<<pq.top () .x<< "-" <<pq.top () .y<< ""; Pq.pop (); } } return 0;}
The 2nd method implements the code:
#include <iostream> #include <queue> #include <algorithm> #include <functional> #include < Vector>using namespace Std;class point{public: friend bool operator < (point a,point b); int x,y;};/ /friend function is implemented outside the class can also implement BOOL operator < (point a,point B) //Priority queue requirements must implement < overloads, or compile errors and int type has the default < function. { return a.x>b.x; Returns the opposite value of the comparison, which is a small-to-large sort of}/** friend function in the class to implement the following class Point{public: friend bool operator < (point A,point b) { return a.x>b.x; } int x, y;}; **/priority_queue<point> PQ; Point P;int Main () { int n; while (Cin>>n) { while (!pq.empty ()) Pq.pop (); while (n--) { cin>>p.x>>p.y; Pq.push (P); } while (!pq.empty ()) { cout<<pq.top () .x<< "-" <<pq.top () .y<< ""; Pq.pop (); } } return 0;}
C + + priority queue (Priority_queue)