Priority Queue Usage
In the priority queue, elements with high priority are first out of the queue.
The standard library uses the < operator of the element type by default to determine the precedence relationship between them.
The first usage of the priority queue is also the most common usage:
priority_queue<int> qi;
The < operator shows the high precedence of the elements in integers.
Therefore, the output in Example 1 is: 9 6 5 3 2
The second method:
In Example 1, what if we want to export the element from small to large?
At this point we can pass in a comparison function, using the Functional.h function object as the comparison function.
priority_queue<int, vector<int>, Greater<int> >qi2;
which
The second parameter is a container type.
The second argument is a comparison function.
Therefore, the output in Example 2 is: 2 3 5 6 9
The third method:
Customize the priority level.
struct node
{
friend bool operator< (node n1, node N2)
{
return n1.priority < n2.priority;
}
int priority ;
int value;
};
In this structure, value is the values and priority is the precedence.
The priority in the element is compared by customizing the operator< operator.
In Example 3, the output is:
Priority value
9 5
8 2
6 1
2 3
1 4
But if the structure is defined as follows:
struct node
{
friend bool operator> (Node n1, node N2)
{
return n1.priority > n2.priority;
}
int priority ;
int value;
};
It will compile but (g++ compiler)
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, so it compiles.
Code Listing
#include<iostream>
#include<Functional>
#include<Queue>
UsingNamespaceStd
struct node
{
FriendBOOL operator<(Node n1, node N2)
{
ReturnN1.priority<n2.priority;
}
IntPriority
IntValue
};
IntMain ()
{
ConstIntLen=5;
IntI
Inta[Len]={3,5,9,6,2};
//Example 1
Priority_queue<Int>Qi
For(I=0; I<Len; I++)
Qi.push (A[i]);
For(I=0; I<Len; I++)
{
cout<<Qi.top ()<<"";
Qi.pop ();
}
cout<<Endl
//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++)
{
cout<<Qi2.top ()<<"";
Qi2.pop ();
}
cout<<Endl
//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;
For(I=0; I<Len; i + + )
qn.push (B[i]);
cout << " priority " << ' \ t ' << value < <endl;
for (i = 0 ; i < len ; i + + )
{
cout << qn.top (). Priority << ' \ t ' <<qn.top () .value<<endl;
qn.pop ();
}
return 0 ;
}
/span> transferred from: http://www.cppblog.com/shyli/archive/2007/04/06/21366.html
C + + priority queue (GO)