//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Example showing how simple priority queues work using C++
#include <iostream>
#include <string>
#include <vector>
#include <queue>
using namespace std;
class PrioritizedWord
{
private:
int m_prio;
string m_word;
public:
explicit PrioritizedWord()
{ }
explicit PrioritizedWord(const std::string& word, const int priority = 0):
m_word(word), m_prio(priority)
{ }
//Operator overloading for priority comparison
const bool operator <(const PrioritizedWord& pW) const
{
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()
{
int somenum = 2;
while(somenum > 0)
{
priority_queue<PrioritizedWord> wordQueue, zahidQueue, *temp=NULL;
//Word Queue first time, Zahid Queue second time
if(somenum%2==0)
{
temp = &wordQueue;
}
else
{
temp = &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
temp->push(PrioritizedWord("First", 23));
temp->push(PrioritizedWord("Second", 23));
temp->push(PrioritizedWord("Third", 23));
temp->push(PrioritizedWord("Fourth", 51));
temp->push(PrioritizedWord("Fifth", -1));
cout<<"\n\nWord Queue elements (All elements lost):"<<endl;
while(!wordQueue.empty())
{
cout<<wordQueue.top()<<" "<<endl;
wordQueue.pop();
}
cout<<"\n\nZahid Queue elements (Elements preserved):"<<endl;
if(!zahidQueue.empty())
{
priority_queue<PrioritizedWord> tempQueue;
while(!zahidQueue.empty())
{
PrioritizedWord &temppW = zahidQueue.top();
cout<<temppW<<" "<<endl;
tempQueue.push(PrioritizedWord(temppW.getWord(), temppW.getPrio()));
zahidQueue.pop();
}
while(!tempQueue.empty())
{
PrioritizedWord &temppW = tempQueue.top();
zahidQueue.push(PrioritizedWord(temppW.getWord(), temppW.getPrio()));
tempQueue.pop();
}
}
cout<<"\n\nZahid Queue - Removing an element and leaving the rest"<<endl;
{
priority_queue<PrioritizedWord> tempQueue;
while(!zahidQueue.empty())
{
PrioritizedWord &temppW = zahidQueue.top();
if(temppW.getWord() != "Second")
{
tempQueue.push(PrioritizedWord(temppW.getWord(), temppW.getPrio()));
zahidQueue.pop();
}
else
{
zahidQueue.pop();
break;
}
}
while(!tempQueue.empty())
{
PrioritizedWord &temppW = tempQueue.top();
zahidQueue.push(PrioritizedWord(temppW.getWord(), temppW.getPrio()));
tempQueue.pop();
}
}
cout<<"\n\nZahid Queue elements after removal of element"<<endl;
while(!zahidQueue.empty())
{
cout<<zahidQueue.top()<<" "<<endl;
zahidQueue.pop();
}
somenum--;
}
return 0;
}
The output is as follows:
No comments:
Post a Comment