Software & Finance





Visual C++ - Priority Queue For Sorting





 

Queue elements are following FIFO structure. But priority queue will check for the priority and then place the element in the right place based on priority.

 

In another words, if you have a priority_queue of integers, then if you iterate through all elements, then it will be in sorted order by Descending (default). However it is bad idea to use priority queue for sorting numbers. I have given here for your understanding purpose only.

 

I have also implemented CMyInts class that overloads the default implementation of Less than < operator with Greater than > operator, so that the queue will following ascending order.

 

#include < iostream >
#include < deque >
#include < queue >
#include < stack >
#include < map >
#include < string >

class CMyInts
{
public:
   bool operator () (const int &lhs, const int &rhs)
   {
      if(lhs < rhs)
         return false;
      return true;
   }
};

void main()
{
   std::cout << "\n\nPriority Queue of Integer Values";
   std::priority_queue < int > myInts;
   myInts.push(10);
   myInts.push(30);
   myInts.push(40);
   myInts.push(20);
   while(myInts.size())
   {
      std::cout  << "\n" << myInts.top();
      myInts.pop();
   }

   std::cout << "\n\n";

   std::cout << "\n\nPriority Queue of Integer Values - Sort Ascending";
   std::priority_queue < int, std::vector < int >, CMyInts> myIntsAsc;
   myIntsAsc.push(10);
   myIntsAsc.push(30);
   myIntsAsc.push(40);
   myIntsAsc.push(20);
   while(myIntsAsc.size())
   {
      std::cout  << "\n" << myIntsAsc.top();
      myIntsAsc.pop();
   }

   std::cout << "\n\n";
}

Sample Output

 

Priority Queue of Integer Values
40
30
20
10

 

Priority Queue of Integer Values - Sort Ascending
10
20
30
40

Press any key to continue . . .