This is just one approach and there may be other approaches. Also notice that I have used a local variable which requires the order to be input. You can also use the static variable approach for this.
//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Example of slightly advanced priority queue making sure that
//along with priorities, queue functionality of FIFO is maintained
#include <iostream>
#include <string>
#include <vector>
#include <queue>
using namespace std;
class PrioritizedWord
{
private:
int m_prio;
string m_word;
int m_order; //To set FIFO operation
public:
explicit PrioritizedWord()
{ }
explicit PrioritizedWord(const std::string& word, const int priority = 0, const int order = 0):
m_word(word), m_prio(priority), m_order(order)
{ }
//Operator overloading for priority comparison
const bool operator <(const PrioritizedWord& pW) const
{
if(m_prio == pW.m_prio)
return (m_order > pW.m_order);
else
return (m_prio < pW.m_prio);
}
//Operator overloading to print output
friend ostream& operator <<(ostream& out, const PrioritizedWord& pW)
{
out<<pW.m_word;
return out;
}
int getPrio(void)
{return m_prio;}
string getWord(void)
{return m_word;}
};
int main()
{
priority_queue<PrioritizedWord> zahidQueue;
//Note the final order will not be the same as the specs do not
//define behaviour in case two numbers with equal priority exist
zahidQueue.push(PrioritizedWord("First", 23, 1));
zahidQueue.push(PrioritizedWord("Second", 23, 2));
zahidQueue.push(PrioritizedWord("Third", 23, 3));
zahidQueue.push(PrioritizedWord("Fourth", 51, 4));
zahidQueue.push(PrioritizedWord("Fifth", -1, 5));
cout<<"\n\nZahid Queue elements :"<<endl;
while(!zahidQueue.empty())
{
cout<<zahidQueue.top()<<" "<<endl;
zahidQueue.pop();
}
return 0;
}
The output is as follows:
No comments:
Post a Comment