Http://www.cnblogs.com/void/archive/2012/02/01/2335224.html
A priority queue is one of the queues, but it can dynamically sort the data in a queue in a way that is customized (priority of the data)
Each push and pop operation, the queue is dynamically adjusted to the way we expect it to be stored.
For example: Our common operation is to sort the data, priority queue default is the high priority of the data
So, regardless of the order in which we push a bunch of numbers, we end up in the queue always top out the largest element.
Usage:
Example: Push the element 5,3,2,4,6 to the priority queue and print its output.
1. The standard library uses the < operator of the element type by default to determine the precedence relationship between them.
Priority_queue<int> PQ;
The < operator shows the high precedence of the elements in integers.
Therefore, the output in Example 1 is: 6 5 4 3 2
2. The smaller the data, the higher the priority
which
The second parameter is a container type.
The second argument is a comparison function.
Therefore, the output in Example 2 is: 2 3 4 5 6
3. Custom priority, overloaded comparison symbol
Overloading Default < Symbols
struct node
{
friend bool operator< (node n1, node N2)
{
return n1.priority < n2.priority;
}
int priority;
int value;
At this point, you need to customize a priority for each element.
Note: The overload > number compiles an error because the standard library uses the < operator of the element type by default to determine the precedence relationship between them.
and the < operator of the custom type has no direct contact with the > operator
Code:
1 #include <iostream>
2 #include <functional>
3 #include <queue>
4 using Namespace stdnamespace std;
5 struct node
6 {
7 friend bool operator< (node n1, node N2)
8 {
9 return n1.priority < n2.priority;
10}
one int priority;
int value;
13};
int main ()
15 {
the const int len = 5;
-int i;
int A[len] = {3,5,9,6,2};
19//Example 1
Priority_queue<int> Qi;
for (i = 0; i < len; i++)
Qi.push (A[i]);
for (i = 0; i < len; i++)
24 {
Cout<<qi.top () << "";
Qi.pop ();
27}
cout<<endl;
29//Example 2
Priority_queue<int, Vector<int>, greater<int> >qi2;
for (i = 0; i < len; i++)
Qi2.push (A[i]);
for (i = 0; i < len; i++)
34 {
Cout<<qi2.top () << "";
Qi2.pop ();
37}
cout<<endl;
39//Example 3
Priority_queue<node> qn;
+ node B[len];
B[0].priority = 6; B[0].value = 1;
B[1].priority = 9; B[1].value = 5;
B[2].priority = 2; B[2].value = 3;
B[3].priority = 8; B[3].value = 2;
b[4].priority = 1; B[4].value = 4;
47
(i = 0; i < len; i++)
Qn.push (B[i]);
cout<< "priority" << "\ T" << "value" <<endl;
Wuyi for (i = 0; i < len; i++)
52 {
Cout<<qn.top () .priority<< ' \ t ' <<qn.top () .value<<endl;
Qn.pop ();
55}
return 0;
57}
"Go" priority queue Priority_queue usage