Tuesday 24 March 2009

Simulating FIFO behaviour with priority queues for equal priorities

In priority queue, the C++ specifications does not define the behaviour of the algorithms when equal-priority items are involved. It is assumed that the ordering is not important in case of a priority queue as long as the same priority items are in correct order as compared to other priorities. For a programmer though this can be important as he expects FIFO ordering for same priority items. To overcome the problem I mentioned in earlier program, we can add another item to get correct FIFO ordering for same priority items.

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