Using a Priority Queue : priority_queue « Queue Stack « C++






Using a Priority Queue

  
#include <iostream>
#include <queue>
#include <string>

using namespace std;

class Message
{
   public:
   Message( string message = "A",string source = "B", int security_level = 0 );

   bool operator<( const Message& rhs ) const;

   string message() const;
   int security_level() const;
   string source() const;

   private:
   string message_, source_;
   int security_level_;
};

inline
Message::Message( string message, string source, int security_level )
   : message_( message ), source_( source ),
     security_level_( security_level )
{}
bool Message::operator<( const Message& rhs ) const
{  return security_level() < rhs.security_level(); }

string Message::message() const
{  return message_; }

string Message::source() const
{  return source_; }

int Message::security_level() const
{  return security_level_; }

int main( )
{
   const char* message[] = { "A","B", "C","D","E","F","G" };
   const char* source[] = { "a", "b", "c","d", "e", "f", "G" };
   const int security_level[] = { 0, 1, 3, 2, 6, 7, 8 };
   const int num_messages = sizeof( security_level ) / sizeof( security_level[0] );

   priority_queue<Message> messages;

   for( int i = 0; i < num_messages; ++i ){
      cout << "Event " << (i+1) << ": Security level - "
         << security_level[i] << "\n\t" << source[i] << " reports "
         << message[i] << endl;

      messages.push( Message( message[i], source[i],security_level[i] ) );
   }

   while( !messages.empty() )
   {
      cout << "Security level - "
         << messages.top().security_level() << "\n\t"
         << messages.top().source() << " reports "
         << messages.top().message() << endl;
      messages.pop();
   }
}
  
    
  








Related examples in the same category

1.priority_queue of double
2.priority_queue: push, pop, top, empty
3.priority_queue: push and size
4.priority_queue: pop
5.priority_queue: top
6.Priority Queue Opertions: empty(), pop(), top(), push()
7.Define your function to Prioritize a priority_queue
8.A priority_queue: size(), top(), empty(), pop()