#include <iostream>
#include <queue>
enum Priority
{
LOW,
MEDIUM,
HIGH
};
class Message
{
public:
Priority mPriority;
int mMessage;
Message(int message)
: mMessage(message), mPriority(MEDIUM)
{}
Message(int message, Priority priority)
: mMessage(message), mPriority(priority)
{}
};
struct PriorityLessThan
{
bool operator()(Message lhs, Message rhs)
{
if ((int)lhs.mPriority < (int)rhs.mPriority)
{
return true;
}
else
{
return false;
}
}
};
int main()
{
std::priority_queue<Message ,
std::vector<Message>,
PriorityLessThan > priorityQueue;
priorityQueue.push(Message(1 )); // 4th or 5th
priorityQueue.push(Message(2, HIGH )); // 1st or 2nd or 3rd
priorityQueue.push(Message(3, LOW )); // 6th or 7th
priorityQueue.push(Message(4, HIGH )); // 1st or 2nd or 3rd
priorityQueue.push(Message(5, LOW )); // 6th or 7th
priorityQueue.push(Message(6, MEDIUM)); // 4th or 5th
priorityQueue.push(Message(7, HIGH )); // 1st or 2nd or 3rd
for (int i = 0; i < 7; i++)
{
std::cout << priorityQueue.top().mMessage << " ";
priorityQueue.pop();
}
std::cout << std::endl;
return 0;
}
// Output: 2 7 4 6 1 3 5
Reference: Josuttis, Nicolai M., The C++ Standard Library: A Tutorial and Reference. New York: Addison-Wesley, 1999, pp. 453-9.
Tuesday, December 19, 2017
C++98: Priority Queues
Priority Queues let items go to the head of the queue based on priority. Items with the same priority are not necessarily taken in order. Here is an example:
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment